2011-05-26 94 views
0

越來越屬性故障那是我的模型:導軌 - 從關係

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" 

由於honorsperson#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的屬性,但是我想獲得它所屬的榮譽創造者和團隊。我怎樣才能做到這一點?

謝謝!

回答

1

你可以通過訪問

ho.person 

ho.group 
0

注:

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

belongs_to :group 

將做同樣的事情,因爲Rails將假設你給它的類和外鍵:group

要獲得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 %> 

可能是搞砸了收件人協會,但我會去看看。