どなたかご教授ください。
collection_selectを使用しcategoryを選び、post(子)とcategory(親)をpostしています
今回質問したいことは"~/posts/2"のページを開いた時、本来であればcategory_id:1を抽出しcategory_id:1の内容(p_cat)を表示させたいのですが、categoryもparams[:id]の2が選択されてしまうことを訂正する方法です。
以下はpostコントローラーのcreateアクションとshowアクションです
def show @post = Post.find(params[:id]) @category = Category.posts.find(params[:category_id]) end # POST /posts # POST /posts.json def create @category = Category.find(params[:post][:p_cat_id]) @post = @category.posts.create(post_params) respond_to do |format| if @post.save format.html { redirect_to @post, notice: 'Post was successfully created.' } format.json { render :show, status: :created, location: @post } else format.html { render :new } format.json { render json: @post.errors, status: :unprocessable_entity } end end end
以下はpostsファイル内のshow.html.erbです
<p> <strong>タイトル:</strong> <%= @post.title %> </p> <p> <strong>名前:</strong> <%= @post.name %> </p> <p> <strong>カテゴリー:</strong> <%= @category.p_cat %> </p>
ルートはこのようになっています
resources :categories do resources :posts end
ちなみに、postの_form.html.erbはこのようになっています
<%= form_for(post) do |f| %> <% if post.errors.any? %> <div id="error_explanation"> <h2><%= pluralize(post.errors.count, "error") %> prohibited this post from being saved:</h2> <ul> <% post.errors.full_messages.each do |message| %> <li><%= message %></li> <% end %> </ul> </div> <% end %> <div class="field"> <%= f.label :title %> <%= f.text_field :title %> </div> <div class="field"> <%= f.label :name %> <%= f.text_field :name %> </div> <%= f.collection_select :p_cat_id, Category.all, :id, :p_cat ,:prompt => "キーワードを選択してください"%> <div class="actions"> <%= f.submit %> </div> <% end %>
回答1件
あなたの回答
tips
プレビュー