My application has Users and Dwellings. When a user creates a dwelling, the user becomes the owner of the dwelling through a rails association. Through my create method, the user_id is successfully assigned to the newly created dwelling in the owner_id column, however the dwelling_id is not propagated to the dwelling_id in the user‘s record. I’m not sure if it is the relationship or method incorrectly set up, but the problem seems to occur when an attempt is made to save the user, as the dwelling is successfully created. Below are my models and method implementations.
Dwelling Model
# dwelling.rb
class Dwelling < ActiveRecord::Base
attr_accessible :street_address, :city, :state, :zip, :nickname
belongs_to :owner, :class_name => "User", :foreign_key => "owner_id"
has_many :roomies, :class_name => "User"
validates :street_address, presence: true
validates :city, presence: true
validates :state, presence: true
validates :zip, presence: true
end
—
User Model
# user.rb
class User < ActiveRecord::Base
attr_accessible :email, :first_name, :last_name, :password, :password_confirmation, :zip
has_secure_password
before_save { |user| user.email = email.downcase }
before_save :create_remember_token
belongs_to :dwelling
has_many :properties, :class_name => "Dwelling", :foreign_key => "owner_id"
...
—
Dwellings Controller (create method)
# dwellings_controller.rb
def create
@dwelling = current_user.properties.build(params[:dwelling])
if @dwelling.save
current_user.dwelling = @dwelling
if current_user.save
flash[:success] = "Woohoo! Your dwelling has been created. Welcome home!"
else
flash[:notice] = "You have successfully created a dwelling, but something prevented us from adding you as a roomie. Please email support so we can try to correct this for you."
end
redirect_to current_user
else
render 'new'
end
end
—
As mentioned above, the dwelling is successfully created but the “…but something prevented us from adding you as a rookie…” flash is triggered from the else conditional.
Update 8/3/12 9:11PM EST
I updated the create action to use user.save! to force the transaction. The following error was output. Apparently the password is required somehow.
ActiveRecord::RecordInvalid in DwellingsController#create
Validation failed: Password can't be blank, Password is too short (minimum is 6 characters), Password confirmation can't be blank
This was an issue with saving the
user. I updated mycreateaction in theDwellingscontroller to to force a save of theuserusinguser.save!to break the application and get an explicit error. Rails complained of a missingpassword(and password length) andpassword_confirmation. I am enforcing apresencevalidation on bothpasswordandpassword_confirmationas well as alengthvalidation onpasswordin myUsermodel. I updated these validations to be enforced only oncreate. This solved the issue. With the validations no longer being enforced onuser.save, thedwelling_idwas successfully added to theuserrecord. The newly implemented code is below.—