I have a dwelling object that is built on a user.
Dwellings Controller (create action)
# 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
The dwelling_id is not being saved to the current_user record. To get more information, I added the bang method (as shown above) to the current_user.save! command. Rails complains that the user‘s password is required to update the record, as shown below.
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
If providing the user’s password through a hidden field isn’t the correct solution – and it does seem insecure – how can I correct this problem? Relevant sections of the user and dwelling model shown below.
#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"
#user.rb
class User < ActiveRecord::Base
attr_accessible :email, :first_name, :last_name, :password, :password_confirmation, :zip, :dwelling_id
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"
Turns out the problem was stemming from my validations in the
Usermodel. Thepresenceandlengthvalidations onpasswordandpassword_confirmationwere being imposed onuser.save, which was failing aspasswordandpassword_confirmationwere not being provided. My update validations appear below.User Model
With this updated implementation, the
useris successfully saved and the appropriate attributes are updated. This is a secondary issue stemming from this original question: In Rails, how can I automatically update a User to own a newly created object of another class within the new object's Create method?