0

I have a comments_controller that uses inherited_resources and deals with this models:Comment (belongs_to Shop and belongs_to User), and Shop (belongs_to User). Rails 4.1.1 and Inherited_resources v is 1.5.0.

Routes are:

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

However, the below code doesn't work:

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 that test creation/deletion of comments tell me Couldn't find User without an ID.

Thanks for any help.

UPD One of the failing tests:

  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
Al17
  • 431
  • 7
  • 20
  • It would be helpful to mention which version of Rails you are on. This gem [inherited resources](https://github.com/josevalim/inherited_resources) is pretty old and its author advises not to use it for Rails 3 and above. – San Sep 19 '14 at 14:23
  • @San I updated. Rails is 4.1.1 – Al17 Sep 19 '14 at 14:39

1 Answers1

1

From your routes, it looks like you want to deal with Comments belonging to a Shop. In this case, you don't need nested_belongs_to, instead change it to belongs_to :shop in your controller and that will take care of it. And add another line belongs_to :user separately.

So, your controller will look like this:

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

  .
  .
  .
end
San
  • 1,954
  • 1
  • 14
  • 18
  • Thanks, I tried and the mistake changed! Now it's `undefined method ``users' for #`.. – Al17 Sep 19 '14 at 14:48
  • Where is the error coming from. Please post the test that you are running and full output. Thanks. – San Sep 19 '14 at 14:50
  • The test with valid info and destruction test are failing either. – Al17 Sep 19 '14 at 15:01