0

我有一个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"
4

2 回答 2

1

原来问题源于我在User模型中的验证。和验证presence和被强加于,这是失败的并且没有被提供。我的更新验证出现在下面。lengthpasswordpassword_confirmationuser.savepasswordpassword_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成功保存并更新了相应的属性。这是源于这个原始问题的次要问题:在 Rails 中,如何自动更新用户以在新对象的 Create 方法中拥有另一个类的新创建对象?

于 2012-08-05T05:40:33.360 回答
0

您不能在表单中的任何位置分配密码,因为用户的密码以无法解密的加密密码摘要格式保存在数据库中(通过 has_secure_password)。(密码是通过单向加密保存的。)所以没有办法把密码放在表单的隐藏字段中的任何地方(无论如何这都是个坏主意)。

检查日志中的 current_user (logger.debug current_user) 以查看 current_user 是否分配了有效用户(带有密码)。

于 2012-08-05T05:20:08.937 回答