首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Rails Inherited_resources多重belongs_to

Rails Inherited_resources多重belongs_to
EN

Stack Overflow用户
提问于 2014-09-19 14:02:38
回答 1查看 750关注 0票数 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。

路线如下:

代码语言:javascript
复制
resources :shop do
  resources :comments, only: [:create, :destroy]
end

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

代码语言:javascript
复制
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是失败的测试之一:

代码语言:javascript
复制
  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
EN

回答 1

Stack Overflow用户

发布于 2014-09-19 14:42:55

从您的路线来看,您似乎想要处理属于CommentsShop。在本例中,您不需要nested_belongs_to,而是在控制器中将其更改为belongs_to :shop,这将处理它。并分别添加另一行belongs_to :user

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

代码语言:javascript
复制
class CommentsController < InheritedResources::Base
  before_filter :authenticate_user!
  belongs_to :shop
  belongs_to :user
  actions :create, :destroy

  .
  .
  .
end
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25935796

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档