使用的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协会的一部分 现在我让所有的行为和失踪的 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 -%>

感谢您的帮助。

有帮助吗?

解决方案

我想你错过了关键的是,发现者和命名范围只返回类,他们正在呼吁。

@acts = Actcategory.theacts(@planning)

@acts是所有Actcategories其中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包含acttype,x的行为时,与相关联的规划,Y

@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%>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top