Reputation: 125
Those are my models:
class Person < ActiveRecord::Base
has_many :honors, :dependent => :destroy, :foreign_key => "honored_id"
has_many :honor_creators, :through => :honors, :source => :person, :foreign_key => "person_id"
class Group
has_many :honorss,:foreign_key => "group_id"
class Honor
belongs_to :person, :class_name => 'Person', :foreign_key => "person_id"
belongs_to :honored, :class_name => 'Person', :foreign_key => "honored_id"
belongs_to :group, :class_name => 'Group', :foreign_key => "group_id"
Since the honors
are shown at the person#show
page, here is my controller:
def show
...
@honors = @person.honors.paginate(:page => params[:page], :per_page => Honor.per_page)
end
And my view:
<% unless @honors.empty? %>
<% @honors.each do |ho| %>
My question is: using the ho
I get all the attributes from the honor
, but I want to get the creater of the honor and the group that it belongs. How can I do that?
Thanks!
Upvotes: 0
Views: 52
Reputation: 9444
Note:
belongs_to :group, :class_name => 'Group', :foreign_key => "group_id"
and
belongs_to :group
will do the same thing because Rails will assume that class and foreign key when you give it :group
.
To get ho.honor_creator
to work (If I'm assuming correctly), you'll want:
class Person < Model
has_many :honors, :foreign_key => :creator_id
end
class Honor < Model
belongs_to :creator, :class_name => "Person"
end
That way, you can set honor.creator_id = params[:user_id]
and then access the Person with ho.creator
.
In other words, I'd redo your models like this:
class Person < ActiveRecord::Base
belongs_to :honor, :foreign_key => :recipient_id
has_many :honors, :foreign_key => :creator_id
class Group
has_many :honors
class Honor
has_many :recipients, :class_name => 'Person' # recipient_id is assumed
belongs_to :creator, :class_name => 'Person' # creator_id is assumed
belongs_to :group # group_id is assumed
I renamed some columns to hopefully make better sense, and this is done off the top of my head, so I'll look at some reference to ensure my accuracy.
This will give you access to honor.creator
and honor.group
.
<% @honors.each do |honor| %>
Honor Creator: <%= honor.creator.name %>
Honor Group: <%= honor.group.name %>
Honor Recipients: <% honor.recipients.each {|recipient| puts recipient} %>
<% end %>
Might have messed up the recipient association, but I'll go look.
Upvotes: 0