Using has many :through
-
18-09-2019 - |
Question
Using has_many => through association.
Here is what i have.
:planning model
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 model
named_scope :theacts, lambda { |my_id|
{:conditions => ['planning_id = ?', my_id] }}
belongs_to :act
belongs_to :planning
:acttype model
has_many :acts
My Problem Starts here. I need to show all Acts by each Act Type from Plannings that is part of the actcategories association Right now i am getting all the acts and missing the actcategories association.
Planning Controller
def show
@planning = Planning.find(params[:id])
@acttypes = Acttype.find(:all, :include => :acts)
@acts = Actcategory.theacts(@planning)
end
Planning Show View
<% @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 -%>
Thanks for any help.
Solution
I think the key thing you're missing is that finders and named scopes only return the Class that they're called on.
@acts = Actcategory.theacts(@planning)
@acts is all the Actcategories where actcategories.planning_id = @planning.id
. They don't necessarily have the required act type.
Really, what I think you're looking for is this named scope:
class Act < ActiveRecord::Base
named_scope :with_planning, lambda do |planning_id|
{ :joins => :actcategories,
:conditions => {:actcategories => {:planning_id => planning_id}}
}
...
end
Which limits acts to those associated with the given planning. This can be called on an association to limit the linked acts to those associated with a specific planning.
Example: @acts contains acts of acttype, x, that are associated with planning, y.
@acts = Acttype.find(x).acts.with_planning(y)
With this named scope this code should accomplish what you were aiming for.
controller:
def show
@planning = Planning.find(params[:id])
@acttypes = Acttype.find(:all, :include => :acts)
end
view:
<% @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%>