This time, I will introduce how to store the information entered in textarea in a variable in the method.
ruby:new.html.erb
<div class="infomation_new">
 <%= form_tag("/infomations",method: :post) do |f|%>
  <p class = "infomation_new_textarea"><%= text_field_tag :talent_name%></p></br>
  <p class = "infomation_new_submit"><%= submit_tag 'Search'%></p>
 <% end %>
</div>
The focus this time is on: talent_name next to text_field_tag. Make this description
infomations_controller.rb
def create
        talent_name = params[:talent_name]
        agent = Mechanize.new
        personal_page = agent.get('https://talent-dictionary.com/' + talent_name)
        aaas = personal_page.at('.talent_name_wrapper')
        @ages = aaas.at('.age').inner_text.delete('age').to_i if aaas.at('.age')
        @names = aaas.at('h1').inner_text  if aaas.at('h1')
        @image_urls = personal_page.at('.main_image img').get_attribute('src') if personal_page.at('.main_image img')
        @infomation = Infomation.where(name: @names).first_or_initialize
        @infomation.age = @ages
        @infomation.image_url = @image_urls
        @infomation.save
end
You can store it in a variable in the method by setting talent_name = params [: talent_name] on the second line. For example, if you enter Taro Yamada
[16, 25] in /home/ec2-user/environment/filebook/app/controllers/infomations_controller.rb
   16:         @ages = aaas.at('.age').inner_text.delete('age').to_i if aaas.at('.age')
   17:         @names = aaas.at('h1').inner_text  if aaas.at('h1')
   18:         @image_urls = personal_page.at('.main_image img').get_attribute('src') if personal_page.at('.main_image img')
   19:         @infomation = Infomation.where(name: @names).first_or_initialize
   20:         @infomation.age = @ages
   21:         @infomation.image_url = @image_urls
   22:         @infomation.save
   23:         byebug
=> 24:     end
   25: end
(byebug) talen_name
*** NameError Exception: undefined local variable or method `talen_name' for #<InfomationsController:0x00007f0fb5777ce0>
Did you mean?  talent_name
nil
(byebug) talent_name
"Yamada Taro"
(byebug) 
That's it.
Recommended Posts