2014-09-19 132 views
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。Ruby on Rails Inherited_resources multiple belongs_to

航线有:

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 
+0

这将有助于何况你是哪个的Rails的版本。这个gem [继承资源](https://github.com/josevalim/inherited_resources)非常古老,它的作者建议不要将它用于Rails 3和更高版本。 – San 2014-09-19 14:23:21

+0

@San I更新。 Rails是4.1.1 – 2014-09-19 14:39:21

回答

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 
+0

谢谢,我试过了,错误改变了!现在它是未定义的方法''用户'#'.. – 2014-09-19 14:48:46

+0

错误来自哪里。请发布您正在运行的测试和完整的输出。谢谢。 – San 2014-09-19 14:50:54

+0

我加了测试。 – 2014-09-19 14:54:54