LoginSignup
0
0

More than 3 years have passed since last update.

textareaで入力した情報をメソッド内の変数に格納する方法

Posted at

今回はtextareaで入力した情報をメソッド内の変数に格納する方法を紹介します。

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 '検索'%></p>
 <% end %>
</div>

今回注目するところはtext_field_tagの隣にある:talent_nameのところです。
この記述をして

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('歳').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

二行目のtalen_name = params[:talent_name]にすることでメソッド内の変数に格納することができます。
例えば山田太郎と入力すると

[16, 25] in /home/ec2-user/environment/filebook/app/controllers/infomations_controller.rb
   16:         @ages = aaas.at('.age').inner_text.delete('歳').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
"山田太郎"
(byebug) 

これでお終いです。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0