わからないこと:Postの新規作成の際に、categoryをどのようにつけるか。
前提:PostモデルとCatgeoryモデルがある。Postモデルには、title,content,catgory_idカラムが存在し、Categoryモデルとアソシエーション済。
<具体的にわからないこと>
/posts/new
form_forを用いて、下記のformを作成した。
上記フォームの画像の中の"Category"というフィールドでcategory_idを数値で設定する
Ruby
1<%= form_for(@post) do |f| %> 2 <%= f.label:title %> 3 <%= f.text_field:title %> 4 5 <%= f.label:content %> 6 <%= f.text_field:content,size:50 %> 7 8 <%= f.label:category %> 9 <%= f.number_field:category %> 10 11 <%= f.submit "提出する" %> 12 <% end %>
そして、コントロラーに移行する。
Ruby
1class PostsController < ApplicationController 2 3 def new 4 @post=Post.new 5 end 6 7 def create 8 category=Category.find(category_params) 9 @post=category.posts.build(post_params) 10 if @post.save 11 render 'normal/home' 12 13 else 14 redirect_to root_url 15 end 16end 17 18 19 private 20 21 def category_params 22 params.require(:post).permit(:category_id) 23 end 24 25 def post_params 26 params.require(:post).permit(:title,:content) 27 end 28 29end
この時に、なぜか、category_idが入りません。createの1行目でつまづきます。
なお
Ruby
1category=Category.find(2)
とした時は、うまく行きました。
なぜ、category_idの値が入らないのか、教えていただけると嬉しいです!
調べてもわかりませんでした。
ご回答いただけると幸いです。
回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2018/05/27 12:59
2018/05/27 13:03