「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