使用には多くの:throughがあります
-
18-09-2019 - |
質問
関連付けを通じて 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
私の問題はここから始まります。全部見せる必要がある 行為 それぞれによって アクトタイプ から 企画 それはの一部です 行為カテゴリー協会今、私はすべての行為を取得していますが、 行為カテゴリー協会.
企画コントローラー
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 はすべての Actcategory です。 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%>
所属していません StackOverflow