通过关联使用has_many =>。
这是我所拥有的。
*规划模式
has_many :acttypes
has_many :actcategories
has_many :acts, :through => :actcategories*acts模式
belongs_to :acttype
has_many :actcategories
has_many :plannings, :through => :actcategories*行动范畴模型
named_scope :theacts, lambda { |my_id|
{:conditions => ['planning_id = ?', my_id] }}
belongs_to :act
belongs_to :planning*行动型模型
has_many :acts我的问题从这里开始。我需要显示所有 acts by每个Act类型的,这是 association的一部分,现在我正在获取所有acts,并且缺少动作类别关联E 213。
规划控制器
def show
@planning = Planning.find(params[:id])
@acttypes = Acttype.find(:all, :include => :acts)
@acts = Actcategory.theacts(@planning)
end规划显示视图
<% @acttypes.each do |acttype|%>
<%= acttype.name %>
<% @acts.each do |acts| %>
<li><%= link_to acts.act.name, myacts_path(acts.act, :planning => @planning.id) %></li>
<% end %>
<% end -%>谢谢你的帮助。
发布于 2009-12-09 04:37:32
我认为您缺少的关键是查找器和命名作用域只返回它们被调用的类。
@acts = Actcategory.theacts(@planning)@acts是actcategories.planning_id = @planning.id中的所有acts类别。他们不一定有必要的行为类型。
真的,我认为你要找的是这个命名的范围:
class Act < ActiveRecord::Base
named_scope :with_planning, lambda do |planning_id|
{ :joins => :actcategories,
:conditions => {:actcategories => {:planning_id => planning_id}}
}
...
end它将行为限制在与给定计划相关的范围内。这可以要求一个协会将相关行为限制在与特定规划有关的行为上。
示例:@acts包含与规划y相关联的行为类型x。
@acts = Acttype.find(x).acts.with_planning(y)有了这个命名的范围,这段代码就能完成你想要的目标。
主计长:
def show
@planning = Planning.find(params[:id])
@acttypes = Acttype.find(:all, :include => :acts)
end意见:
<% @acttypes.each do |acttype| %>
<h2> <%= acttype.name %><h2>
<% acttype.acts.with_planning(@planning) do |act| %>
This act belongs to acttype <%= acttype.name%> and
is associated to <%=@planning.name%> through
actcatgetories: <%=act.name%>
<%end%>
<%end%>https://stackoverflow.com/questions/1871308
复制相似问题