Ruby on Rails Inherited_resources несколько принадлежат

У меня есть 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

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
Другие вопросы по тегам