Rails Active Record表关联

时间:2009-03-11 19:02:09

标签: ruby-on-rails activerecord

我的问题涉及一些不同的有效记录

class Respondent < ActiveRecord::Base
has_many :phone_numbers, :dependent => :destroy
has_many :email_addresses, :dependent => :destroy
belongs_to :phone_number, :foreign_key=> "primary_phone_id"
belongs_to :email_address, :foreign_key=> "primary_email_id"
end

class User < Respondent
end

class EmailAddress < ActiveRecord::Base
belongs_to :respondent
has_one :respondent
end

这些表的架构是

create_table "email_addresses", :force => true do |t|
  t.string   "email"
  t.integer  "respondent_id"
end

create_table "respondents", :force => true do |t|
  t.string   "first_name"
  t.string   "last_name"
  t.integer  "primary_email_id"
  t.integer  "primary_phone_id"
  t.string   "type"
end

我想要完成的是让受访者和用户能够拥有多个电子邮件地址但只有一个主要邮件地址。因此,电子邮件记录和受访者记录了彼此之间的链接。所有电子邮件地址都存储在email_address记录中并引用受访者,而受访者记录只有一封电子邮件的身份。

在UserController中,以下代码失败

def create
    @user = User.new(params[:user])
    @primary_email = EmailAddress.new(params[:primary_email])
    User.transaction do
      @user.primary_email = @primary_email  <=Undefined Method primary_email=
      @user.save!
      @primary_email.save!
      redirect_to :action => :show, :id => @user
    end
end

首先,这甚至可能是我在做什么? 如何修改代码以使此控制器代码有效?

1 个答案:

答案 0 :(得分:2)

是的,您只需要让受访者拥有相关的主要电子邮件:

has_one :primary_email, :class_name => "EmailAddress"