사용하는 것은 다음과 같습니다
-
18-09-2019 - |
문제
협회를 통해 has_many => 사용.
여기 내가 가진 것이 있습니다.
: 계획 모델
has_many :acttypes
has_many :actcategories
has_many :acts, :through => :actcategories
: Acts Model
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 Association지금 나는 모든 행위를 얻고 있으며 ActCategories Association.
계획 컨트롤러
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
. 반드시 필요한 ACT 유형을 가지고있는 것은 아닙니다.
정말로, 당신이 찾고 있다고 생각하는 것은이 이름의 범위입니다.
class Act < ActiveRecord::Base
named_scope :with_planning, lambda do |planning_id|
{ :joins => :actcategories,
:conditions => {:actcategories => {:planning_id => planning_id}}
}
...
end
주어진 계획과 관련된 행동을 제한합니다. 이는 연결된 행위를 특정 계획과 관련된 행위로 제한하기 위해 협회에서 호출 될 수 있습니다.
예 : @Acts에는 계획과 관련된 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%>
제휴하지 않습니다 StackOverflow