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 アソシエーション一部である計画から各アクト タイプごとにすべてのアクトを表示する必要があり ます。

プランニング コントローラー

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 は、すべての Actcategoriesactcategories.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 に関連付けられた acttype 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 に答える