【问题标题】:Rendering Associate Data (has_many, :through) - Rails渲染关联数据 (has_many, :through) - Rails
【发布时间】:2012-12-09 17:27:52
【问题描述】:

我有两个定义页面内容(广告类型)的导航栏(展示位置和广告)。第一个导航栏,placement,总是在顶部可见。第二个导航栏广告将根据在展示位置顶部选择的属性呈现在页面左侧。模型展示位置和模型广告具有多对多的关系。如何根据在顶部导航栏中选择的属性(展示位置)在 html 中呈现第二个导航广告?

两种导航模型是:

class Placement < ActiveRecord::Base  
  attr_accessible :placementname  
  has_many :adtypes, :foreign_key => "placement_id"  
  has_many :ads, :through => :adtypes   
end


class Ad < ActiveRecord::Base  
  attr_accessible :adname  
  has_many :adtypes, :foreign_key => "ad_id"  
  has_many :placements, :through => :adtypes  
end

这里是内容的模型,广告类型,取决于导航栏中选择的属性:

class Adtype < ActiveRecord::Base  
  attr_accessible :adtype_screenshot, :location, :placement_screemshot, :specs  
  belongs_to :placements  
  belongs_to :ads  
end

这是我的模式数据库:

ActiveRecord::Schema.define(:version => 20121127052112) do  
  create_table "ads", :force => true do |t|  
    t.string   "adname"  
    t.datetime "created_at"  
    t.datetime "updated_at"  
  end 

  create_table "adtypes", :force => true do |t|  
    t.integer  "placement_id"  
    t.integer  "ad_id"  
    t.string   "location"  
    t.string   "placement_screenshot"  
    t.string   "adtype_screenshot"  
    t.string   "specs"  
    t.datetime "created_at"  
    t.datetime "updated_at"  
  end

  create_table "placements", :force => true do |t|  
    t.string   "placementname"  
    t.datetime "created_at"  
    t.datetime "updated_at"  
  end    
end  

这是我的 routes.rb 文件:

  resources :placements do  
    resources :ads do  
      resources :adtypes do  
      end  
    end  
  end  

这是我如何呈现我的顶部导航 (_navigation.html.erb) 并将每个属性链接到以展示位置 ID (http://localhost:3000/placements/2) 结尾的新网址

<% Placement.all.each do |placement| %>  
  <li ><%= link_to placement.placementname, placement_path(placement.id) %> </li>  
<%end%>  

【问题讨论】:

  • 需要哪些控制器动作或动作来呈现 ad 导航栏?它只是placements#show 还是应该是整个网站的标准模板?
  • 它应该是整个站点。虽然我刚刚找到了解决方案。首先,我错误地将这些作为复数:belongs_to :placements belongs_to :ads 所以我只是去掉了“s”并以这种方式呈现我的广告(广告视图显示):
  • 感谢您对此进行调查
  • 对不起,我应该听懂了。您可能想要创建一个答案并接受它。
  • 标签: ruby-on-rails model controller associations render


    【解决方案1】:

    找到解决方案:首先,我错误地将这些作为复数:

    belongs_to :placements 
    belongs_to :ads 
    

    所以我只是去掉了“s”并以这种方式呈现我的广告(广告视图显示):

    <% @placement.ads.all.each do |ad| %>  
    <%= link_to ad.adname, placement_ad_path(@placement, ad) %>  
    <%end%>
    

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签