Ruby on rails 如何在rails中实现多级模型引用

Ruby on rails 如何在rails中实现多级模型引用,ruby-on-rails,associations,rails-activerecord,Ruby On Rails,Associations,Rails Activerecord,我有下面的模型结构。我需要添加验证,这样只有餐厅和餐厅活动的正确用户才能编辑/删除它们 class User < ActiveRecord::Base has_many :restaurants, dependent: :destroy end class Restaurant < ActiveRecord::Base belongs_to :user validates :user_id, presence: true has_many :

我有下面的模型结构。我需要添加验证,这样只有餐厅和餐厅活动的正确用户才能编辑/删除它们

class User < ActiveRecord::Base 
    has_many :restaurants, dependent: :destroy
end

class Restaurant < ActiveRecord::Base

    belongs_to :user
    validates  :user_id, presence: true

    has_many :campaigns, dependent: :destroy
end

class Campaign < ActiveRecord::Base
    belongs_to :restaurant
end
我怎样才能获得这项津贴

添加

我尝试的是启用此方法,仅允许拥有活动的用户编辑/删除/查看:

    def correct_user
        @user = User.find_by(params[:id])
        @campaign = @user.campaigns.find_by(params[:id])
        redirect_to root_url if @campaign.nil?
    end
在控制器中,我有:

before_action :correct_user,   only: [:index, :edit, :update, :show, :destroy]

但是,这种方法虽然不存在错误,但不会阻止任何其他用户看到其他用户的活动。因此,使用
@campaign=@user.campaign.find_by(params[:id])
的路由不正确。

如果您有嵌套路由,如

resources :restaurants do
  resources :campaigns
end
然后URL将包含餐厅id,例如:

restaurants/:restaurant_id/campaigns/:id/edit
然后您可以在控制器中执行此操作

@restaurant = current_user.restaurants.find(params[:restaurant_id])
@campaign = @restaurant.campaigns.find(params[:id])

你有很多:活动,通过:餐馆吗?是的,这将为你构建sql。查看“has_many through”了解更多详细信息:您还需要更改
@user.campaims.find(params[:id])
这不起作用,如果调用当前的\u用户方法没有引发错误,并且您能够调用.campairs方法,则
@restaurant
@campaign
都将返回null,这可能意味着当前用户没有餐厅。不,当前用户有几个restaurants@Eatlon,您能否显示您正在点击的路线和控制器操作?
@restaurant = current_user.restaurants.find(params[:restaurant_id])
@campaign = @restaurant.campaigns.find(params[:id])