1

目前我正在开发 CRM 应用程序作为演示项目。目前,我很难理解如何从另一个对象访问一个对象的属性。我正在尝试按照以下方式做一些事情:

 <%= 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 属性?

4

1 回答 1

1

使用delegate方法:

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

然后在您的视图中,您可以从委托的对象访问委托属性:

<%= note.first_name %>
于 2013-08-19T03:57:19.137 回答