Rails - 从关系中获取属性的麻烦

时间:2011-05-26 17:10:31

标签: ruby-on-rails ruby-on-rails-3 view

这些是我的模特:

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"

由于honors显示在person#show页面,因此这是我的控制器:

def show
  ...
  @honors = @person.honors.paginate(:page => params[:page], :per_page => Honor.per_page)
end

我的观点:

<% unless @honors.empty? %>
<% @honors.each do |ho| %>

我的问题是:使用ho我获得了honor的所有属性,但我希望得到荣誉的创建者及其所属的群体。我怎么能这样做?

谢谢!

2 个答案:

答案 0 :(得分:1)

您可以通过访问

来实现
ho.person

ho.group

答案 1 :(得分:0)

注意:

belongs_to :group, :class_name => 'Group', :foreign_key => "group_id"

belongs_to :group

会做同样的事情,因为当你给它:group时,Rails会假设该类和外键。

ho.honor_creator工作(如果我假设正确),您需要:

class Person < Model
  has_many :honors, :foreign_key => :creator_id
end

class Honor < Model
  belongs_to :creator, :class_name => "Person"
end

这样,您可以设置honor.creator_id = params[:user_id],然后使用ho.creator访问此人。

换句话说,我会像这样重做你的模型:

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

我重新命名了一些专栏,希望能有更好的理解,这是我的头脑,所以我会看一些参考来确保我的准确性。

这样,您就可以访问honor.creatorhonor.group

<% @honors.each do |honor| %>
  Honor Creator: <%= honor.creator.name %>
  Honor Group: <%= honor.group.name %>
  Honor Recipients: <% honor.recipients.each {|recipient| puts recipient} %>
<% end %>

可能搞砸了收件人协会,但我会去看看。