我在提交表单后收到奇怪的错误。一直在努力解决这个问题了几个小时..嵌套的资源参数没有在form_for中正确设置
No route matches {:action=>"show", :controller=>"items", :item_id=>"141", :matter_id=>"3"} missing required keys: [:id]
的参数是:
{"utf8"=>"✓",
"authenticity_token"=>"w0D7XmX2X2/ZMU19T6RlMvWCEClXnCFFOR+4EdIFvWg=",
"comment_item"=>{"item_id"=>"",
"name"=>"kaljdf",
"body"=>"yet another comment test"},
"commit"=>"Post Comment",
"matter_id"=>"3",
"item_id"=>"141"}
我有以下型号:
class Matter < ActiveRecord::Base
has many :discoveries
delegate :items, to: :discoveries
end
class Discovery < ActiveRecord::Base
belongs_to :matter
scope :items, -> { where(type: 'Item') }
end
class Item < Discovery
has_many :comment_items
end
class CommentItem < ActiveRecord::Base
belongs_to :item
end
控制器:
class ItemsController < DiscoveriesController
def show
@item = Item.find(params[:id])
@comment_item = CommentItem.new
end
def edit
@item = Item.find(params[:id])
end
def new
@item = Item.new
end
end
class CommentItemsController < ApplicationController
before_action :set_comment_item, only: [:show, :edit, :update, :destroy]
def new
@item = Item.find(params[:item_id])
@comment_item = @item.comment_item.new
end
def create
@item = Item.find(params[:item_id])
@comment_item = @item.comment_items.new(comment_item_params)
if @comment_item.save
flash[:notice] = 'Comment was successfully created'
redirect_to matter_item_url(matter_id: params[:matter_id])
else
flash[:notice] = "Error creating comment: #{@comment.errors}"
redirect_to matter_item_url(@matter, @item)
end
end
def destroy
@comment_item = CommentItem.find(params[:id])
@comment_item.destroy
redirect_to(@comment_item.item)
end
private
def set_comment_item
@comment_item = CommentItem.find(params[:id])
end
def comment_item_params
params.require(:comment_item).permit(:name, :body, :item_id, :matter_id)
end
end
该项目资源的表演动作:
<p>
<strong>Matter:</strong>
<%= @item.matter_id %>
</p>
<p>
<strong>Content:</strong>
<%= @item.content %>
</p>
<hr />
<%= form_for @comment_item, url: matter_item_comment_items_path(matter_id: @item.matter, item_id: @item.id) do |f| %>
<% if @comment_item.errors.any? %>
<ul>
<% @comment_item.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
<% end %>
<%= f.hidden_field :item_id %>
<p>
<%= f.label :name %><br />
<%= f.text_field :name %>
</p>
<p>
<%= f.label :body %><br />
<%= f.text_area :body %>
</p>
<p>
<%= f.submit "Post Comment" %>
</p>
<% end %>
<%= render :partial => 'comment_item', :collection => @item.comment_items %>
<%= link_to 'Edit', edit_matter_item_path(id: @item.id) %> |
<%= link_to 'Back', matter_items_path %>
路线
resources :items do
resources :comment_items
end
resources :matters do
resources :items do
resources :comment_items
end
end
当在控制台CommentItems看,我看到的评论实际上添加模型与他们正确的ID,但他们似乎并没有作为参数传递..我错过了什么?
我查看Rails 4 form_for double nested comments和Rails 3.2 - Nested Resource Passing ID,但我并没有太多的运气..
我真的很感谢您的帮助!
您的请求将会上述ItemsController代替CommentItemsController – 2014-11-21 01:02:28
谢谢!你在哪里看到? – casekey 2014-11-21 02:03:30