Rails:引用has_many中的连接表属性:通过视图中的关系?

时间:2012-01-30 03:57:00

标签: ruby-on-rails activerecord

我有三个型号:

class Registry < ActiveRecord::Base
  has_many :registry_item
  has_many :item, :through => :registry_item
end  

class RegistryItem < ActiveRecord::Base
  belongs_to :registry
  belongs_to :item
end

class Item < ActiveRecord::Base
end

RegistryItem具有布尔属性purchased

<% @registry.item.each do |item| %>
  <div>
    <h4><%= item.title %></h4>
    <p><%= item.description %></p>
    # Here, I'd like to display "PURCHASED" if 
    # the registry_item's purchased property is true
    <% if [?] %>PURCHASED<% end %>
  </div>
<% end %>

我真的想以某种方式引用purchased中的[?]属性 - 但它是registry_item的属性 - 而不是registry或{{ 1}}。

解决这个问题的一种方法是迭代连接模型对象:

item

另一种方法是在<h2>Items</h2> <% @registry.registry_item.each do |item| %> <div> <h4><%= registry_item.item.title %></h4> <p><%= registry_item.item.description %></p> <% if registry_item.purchased %>PURCHASED<% end %> </div> <% end %> 上定义purchased?函数,该函数采用registry参数。

item

我认为必须有一个更清洁的方式。

3 个答案:

答案 0 :(得分:0)

首先,请注意,当你有一个has_many关系时,你应该使用复数:

has_many :registry_items

现在,我假设你想要一个Item,一个Registry和一个RegisteredItem类。这需要一个has_many通过关联,如:

class Registry < ActiveRecord::Base 
  has_many :items, :through => :registered_items 
end

如果你这样做,你现在可以拥有一个注册对象,并执行以下操作:

registry.items.each do |i|
  if i.registered_item.status == 'registered'
     whatever....
  end
end

答案 1 :(得分:0)

迭代连接模型对象是干净的。

答案 2 :(得分:0)

这里讨论了非常相似的东西,并且发布了一个很好的解决方案。

Scope with join on :has_many :through association

它过滤了数据库中的关系,而不是遍历ruby中的所有内容。