如何使用belongs_to / has_many关系在Active Admin索引中显示关联模型的属性(Rails 3.2 / Active Admin)
我正在建立一个每日交易Rails应用程序来学习RoR。
我在过去的几个小时内遇到了一个问题:我无法获得活动管理员上其他相关模型的模型属性。 让我告诉你确切的问题:
我有两种模式:品牌(即交易的品牌)和交易。 交易属于品牌,但品牌可以有许多交易。
models / deal.rb是这样的:
class Deal < ActiveRecord::Base belongs_to :brand
我们有models / brand.rb:
class Brand < ActiveRecord::Base has_many :deals attr_accessible :name
我在我的迁移中做了t.belongs_to所以这没关系。
在Active Admin的交易’创建表单中,我输入与交易相关联的品牌作为管理员:
管理员/ game.rb
ActiveAdmin.register Deal do # -- Form ----------------------------------------------------------- form do |f| f.inputs "Brand (ie client)" do f.input :brand_id, :label => "Select a brand:", :as => :select, :collection => Brand.all end
它工作得很好,我可以创建特定品牌的优惠。 但我无法在我的交易列表中显示品牌的名称 :
ActiveAdmin.register Deal do index do selectable_column # id_column column :title column :deal_amount column :brand do |deal| link_to deal.brand.name end
……不起作用。
我怎样才能做到这一点 ?
我尝试了一切但我基本上不知道如何获取品牌的名称,因为它与Deal的表中的brand_id相匹配 。
任何帮助赞赏。
show do |f| panel "Subject" do attributes_table_for f, :name, :description, :is_visible end panel "Pages in List View" do table_for(f.pages) do |page| column :name column :permalink column :is_visible end end panel "Pages in View " do div_for(f.pages) do |page| panel page.name do attributes_table_for page, :name, :description, :is_visible end end end end end
您可以使用与父模型相同的样式执行嵌套关系
似乎缺少几件事:
class Deal < ActiveRecord::Base belongs_to :brands, foreign_key: :brand_id, class_name: 'Brand' end
这假设您是partner
成为Brand
而您的架构使用brand_id
作为该关系。
在您的表单中,您可以简单地使用:
form do |f| f.inputs "Brand (ie client)" do f.input :partner, label: 'Select a brand:' end end
您的link_to
调用实际上不会以您拥有的方式链接到url。
column :brand do |deal| link_to deal.partner.name, admin_brand_path(deal.partner) # or simpler auto_link deal.partner end
我强烈建议您尝试在命名方面保持一致,因为它会使事情变得更加混乱,并且需要更少的代码才能使事情发挥作用。 即
class Deal < ActiveRecord::Base belongs_to :brand end f.input :brand, label: 'Select a brand:' auto_link deal.brand
您的数据库列仍可以命名为brand_id
。