stellard
stellard

Reputation: 5314

Rails Active Record table associations

My question involves a few different active records

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

The schema for these tables are

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

What I am trying to accomplish is to have the respondents, and therefore users, capable of having multiple email address but only one primary. For this reason the email record and respondents record link to one another. All of the email address are stored in the email_address record and reference the respondent, and the respondent record has an id to only one email.

In the UserController the following code fails

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

First, is this even possible what I am doing? How can I modify the code to make this controller code work?

Upvotes: 1

Views: 177

Answers (1)

Gareth
Gareth

Reputation: 138012

Yes, you just need Respondent to have as associated primary email:

has_one :primary_email, :class_name => "EmailAddress"

Upvotes: 2

Related Questions