Rails:一个命令中的多级模型引用

时间:2014-09-07 17:47:23

标签: ruby-on-rails activerecord content-management-system

我正在使用rails构建CMS,并且目前需要使用动态多级层次结构实现来访问特定用户拥有的特定餐馆的广告系列。简而言之,我创建的数据模型就是这样:

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

目前我试图用一系列点操作来实现:

 @user.restaurant.campaigns.(method)

然而,这只是NoMethodErrors undefined method广告系列中的show产生的结果。为#

操作步骤如下:1)用户登录,2)用户显示他们拥有的餐馆列表, 3)用户点击某个餐馆并动态更改视图以显示餐馆广告系列。 是否有正确的方法在rails中实现多级动态模型引用,以便用户可以完成概述的操作并保持在一个页面内并避免导航?

编辑更新后的补充

目前我的用户<% provide(:title, @user.name) %> <div class="row"> <aside class="span4"> <section> <h1> <%= gravatar_for @user %> <%= @user.name %> </h1> </section> <section> <% if @user.locations.any? %> <div> <%= link_to "Start a Campaign", newcampaign_path, class: "btn btn-medium btn-primary" %> </div> <%= link_to "Manage Locations", uploadlocations_path %> <% else %> <%= link_to "Upload Locations", uploadlocations_path, class: "btn btn-medium btn-primary" %> <% end %> </section> <section> <%# disply list of restaurants%> <%= link_to "Add New Restaurant", newrestaurant_path, class: "btn btn-medium btn-primary" %> <ul class ="campaigns"> <%= render @restaurants %> </ul> </section> </aside> <div class="span8"> <% if @restaurants.any? %> <ol class="campaigns"> <%= render @campaigns, object: @restaurants %> </ol> <% end %> </div> </div> 为:

render @restaurants

用户可以在<ul> <span class="content"> <%= link_to restaurant.name, '#' %> </class> </ul> 的侧边菜单中点击特定餐厅,这将转到部分:

<%= render @campaigns, object: @restaurants %>

如何让用户点击菜单中的餐馆,并将选中的特定餐厅发回用户show页面的{{1}}?

1 个答案:

答案 0 :(得分:0)

@restaurant = @user.restaurants.find {|r| r.id == 1 } # or select your particular restaurant
@restaurant.campaigns # 1 query for getting all campaigns for a specific user-restaurant pair

或者您可能希望加载餐馆和广告系列

@user = User.includes(restaurants: :campaigns)

从1 + n(餐馆)查询到1 + 1 + 1查询(用户,所有餐馆,然后是所有广告系列)


编辑(或):

class User < ActiveRecord::Base 
  has_many :restaurants, dependent: :destroy, inverse_of: :user
  has_many :campaigns, through: :restaurants
end

class Restaurant < ActiveRecord::Base
  belongs_to :user, inverse_of: :restaurants
  validates  :user_id, presence: true

  has_many :campaigns, dependent: :destroy, inverse_of: :restaurant
end

class Campaign < ActiveRecord::Base
  belongs_to :restaurant, inverse_of: :campaigns
end

控制器:

@user = User.includes(campaigns: :restaurant)
@restaurant_campaigns = Hash.new([]).merge @user.campaigns.group_by(&:restaurant)
@restaurants = @restaurant_campaigns.keys

的观点:

@restaurants.each do |restaurant|
  @restaurant_campaigns[restaurant] # campaigns for user-restaurant pair
end