我有一个dwelling
对象构建在user
上。
Dwellings Controller(创建行动)
# 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"
答案 0 :(得分:1)
原来问题源于我在User
模型中的验证。 presence
和length
上的password
和password_confirmation
验证强加于user.save
,其失败为password
和password_confirmation
没有被提供。我的更新验证显示在下方。
用户模型
#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_create :create_remember_token
belongs_to :dwelling
has_many :properties, :class_name => "Dwelling", :foreign_key => "owner_id"
validates :first_name, presence: true, length: { maximum: 50 }
validates :last_name, presence: true, length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true,
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :password, presence: { :on => :create }, length: { minimum: 6, :on => :create }
validates :password_confirmation, presence: { :on => :create }
通过此更新实施,user
已成功保存,并且相应的属性已更新。这是源于这个原始问题的第二个问题: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?
答案 1 :(得分:0)
您无法在表单中的任何位置分配密码,只是因为用户的密码以加密的密码摘要格式保存在数据库中(通过has_secure_password),无法解密。 (密码以单向加密方式保存。)因此无法将密码输出放入表单隐藏字段的任何位置(无论如何这都是个坏主意)。
检查日志中的current_user(logger.debug current_user),看看current_user是否分配了有效用户(带密码)。