我有一个dwelling
建立在user
.
住宅控制器(创建动作)
# 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
未dwelling_id
保存到current_user
记录中。为了获得更多信息,我在命令中添加了 bang 方法(如上所示)current_user.save!
。Rails 抱怨user
更新记录需要密码,如下所示。
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
如果通过隐藏字段提供用户密码不是正确的解决方案——而且看起来确实不安全——我该如何解决这个问题?user
和模型的相关部分dwelling
如下所示。
#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"