0

我有一个comments_controller使用inherited_resources和处理这个模型:Comment (belongs_to Shop and belongs_to User)Shop (belongs_to User)Rails 4.1.1和 Inherited_resources v 是 1.5.0。

路线是:

resources :shop do
  resources :comments, only: [:create, :destroy]
end

但是,下面的代码不起作用:

class CommentsController < InheritedResources::Base
  before_filter :authenticate_user!
  nested_belongs_to :user, :shop
  actions :create, :destroy

  def create
    @comment = build_resource
    @comment.shop = Shop.find(params[:hotel_id])
    @comment.user = current_user

    create!
  end

  def destroy
    @hotel = Shop.find(params[:hotel_id])
    @comment = Comment.find(params[:id])
    @comment.user = current_user

    destroy!
  end

 private

   def permitted_params
     params.permit(:comment => [:content])
   end

Rspec 测试创建/删除评论告诉我Couldn't find User without an ID

谢谢你的帮助。

UPD失败的测试之一:

  let(:user) { FactoryGirl.create(:user) }
  let(:shop) { FactoryGirl.create(:shop, user: user) }

  describe "comment creation" do
    before { visit shop_path(shop) }

    describe "with invalid information" do
      it "should not create a comment" do       
        expect { click_button "Post a comment" }.not_to change(Comment, :count)
      end
    end
4

1 回答 1

1

从您的路线来看,您似乎想要处理Comments属于Shop. 在这种情况下,您不需要nested_belongs_to,而是belongs_to :shop在您的控制器中将其更改为 ,这将处理它。并单独添加另一行belongs_to :user

因此,您的控制器将如下所示:

class CommentsController < InheritedResources::Base
  before_filter :authenticate_user!
  belongs_to :shop
  belongs_to :user
  actions :create, :destroy

  .
  .
  .
end
于 2014-09-19T14:42:55.283 回答