LoginSignup
2
0

More than 5 years have passed since last update.

基本的なformの作成の仕方

Last updated at Posted at 2018-02-20

「form_for @hoge」でcreateとupdateを自動で認識してくれる
formのセレクトボックスなどは

を参照。

qiita.rb
<%= form_for @listing do |f| %>
  <p><%= f.label "お家の種類" %>
  <%= f.select :home_type, [["一軒家","一軒家"], ["マンション","マンション"], ["アパート","アパート"]], 
   {prompt:"選択してください"}, {required: 'true', autofocus: 'true', class: 'form-control'} %>

  <p><%= f.label "ペットの種類" %>
  <%= f.select :pet_type, [["犬","犬"], ["猫","猫"], ["鳥類","鳥類"], ["爬虫類","爬虫類"], ["魚類","魚類"], ["両生類","両生類"], ["その他","その他"]], 
  {prompt:"選択してください"}, {required: 'true', autofocus: 'true'} %>

  <p><%= f.label "ペットの飼育歴" %>
  <%= f.select :breeding_years, [["1年",1], ["2年",2], ["3年",3], ["4年",4], ["5年",5], ["6年以上",6]], {prompt:"選択してください"}, 
  {required: 'true', autofocus: 'true'} %>

  <p><%= f.label "ペットのサイズ" %>
  <%= f.select :pet_size, [["小型","小型"], ["中型","中型"], ["大型","大型"], ["超大型","超大型"]], {prompt:"選択してください"}, 
  {required: 'true', autofocus: 'true', class: 'form-control'} %>

  <p><%= f.submit "保存" %>
<% end %>

コントローラーは以下のように編集。ストロングパラメーターの指定も忘れない

qiita.rb
    def new
    @listing = current_user.listings.new
  end

  def create
    @listing = current_user.listings.new(listing_params)
    if @listing.save
      redirect_to edit_listing_path(@listing),notice:"リスティングを作成・保存しました"
    else 
      render new_listing_path(@listing),notice:"リスティングを作成・保存できませんでした"
    end
  end
   :
   :
   :
  private
    def listing_params
      params.require(:listing).permit(:home_type,:pet_type,:pet_size,:breeding_years)
    end
2
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
2
0