2014-09-19 123 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