2013-08-19 89 views
1

目前我正在將CRM應用作爲演示項目。目前,我無法圍繞如何訪問另一個對象的屬性。我試圖做一些事情:訪問Rails中另一個對象的屬性

<%= note.client.first_name %> 

在這種情況下,我有一個筆記爲每個客戶端和兩者之間建立適當的關聯。該模型看起來像這樣:

class Note < ActiveRecord::Base 
    belongs_to :client 
    belongs_to :user 
end 

class Client < ActiveRecord::Base 
    has_many :users 
    has_many :notes 
end 

和數據庫看起來像這樣:

class CreateUsers < ActiveRecord::Migration 
    def change 
    create_table :users do |t| 
    t.string :first_name 
    t.string :last_name 
    t.string :designation 
    t.string :phone 
    t.string :email 
    t.string :password_digest 

    t.timestamps 
    end 
    end 
end 

是否有訪問的任何簡單的方法:用筆記所關聯的客戶端id的FIRST_NAME財產?

+0

class Note < ActiveRecord::Base delegate :first_name, to: :client end 

那麼在你看來,你可以到其被授權訪問對象的委託財產的用戶或:注意? – shiva

回答

1

使用delegate方法:與關聯

<%= note.first_name %> 
+0

我認爲生成的方法應該是'client_first_name'? –

+0

僅當使用'prefix:true'選項調用該方法時纔有效。 – bgates

+0

是的,你是對的。我個人更喜歡'prefix:true'選項。 –

相關問題