我的应用程序有Users
和Dwellings
。当 auser
创建 adwelling
时,user
成为through a rails 关联的owner
。dwelling
通过我的create
方法,user_id
已成功分配给列中新创建dwelling
的owner_id
,但是dwelling_id
没有传播到dwelling_id
的user
记录中。我不确定是否是关系或方法设置不正确,但是当尝试保存 时似乎会出现问题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"
validates :street_address, presence: true
validates :city, presence: true
validates :state, presence: true
validates :zip, presence: true
end
--
用户模型
# 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.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
已成功创建,但从else
条件触发了“...但有些东西阻止我们将您添加为新秀...”闪光灯。
更新 2012 年 8 月 3 日晚上 9:11 东部标准时间
我更新了create
用于user.save!
强制交易的操作。输出以下错误。显然以某种方式需要密码。
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