2

通过关联使用 has_many =>。

这就是我所拥有的。

:规划模型

has_many :acttypes
has_many :actcategories
has_many :acts, :through => :actcategories

:行为模型

belongs_to :acttype
has_many :actcategories
has_many :plannings, :through => :actcategories

:actcategories 模型

named_scope :theacts, lambda { |my_id|
{:conditions => ['planning_id = ?', my_id] }} 
belongs_to :act
belongs_to :planning

:acttype 模型

has_many :acts

我的问题从这里开始。我需要从属于 actcategories 关联Plannings中按每个Act Type显示所有Act 现在我正在获取所有的 act 而缺少actcategories 关联

计划控制器

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 -%>

谢谢你的帮助。

4

1 回答 1

1

我认为您缺少的关键是查找器和命名范围仅返回它们被调用的类。

@acts = Actcategory.theacts(@planning)

@acts 是actcategories.planning_id = @planning.id. 他们不一定具有所需的行为类型。

真的,我认为您正在寻找的是这个命名范围:

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%>
于 2009-12-09T04:37:32.673 回答