2009-12-09 1 views
2

has_many => 연결을 사용합니다.많이 사용함 : through

내가 가진 것은 다음과 같습니다.

: 계획 모델

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 협회 의 일부입니다 Plannings에서 각 행위 유형 모든 를 표시해야합니다. 어떤 도움

계획 컨트롤러

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

감사합니다.

답변

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에는 계획과 관련된 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 <%[email protected]%> through 
    actcatgetories: <%=act.name%> 
    <%end%> 
<%end%>