【发布时间】:2012-08-02 14:11:30
【问题描述】:
我正在尝试在两个现有模型User 和Dwelling 之间创建特殊关系。 Dwelling 在创建时只有一个所有者(Dwelling belongs_to :user、User has_one :dwelling)。但是其他用户可以添加到这个Dwelling 为Roomies(现在没有为此创建模型,Roomie 是一个概念关系)。
我认为我不需要单独的模型,而是需要与现有模型建立特殊关系,但我可能错了。我认为需要使用Users 表中的user_id 进行引用。我不确定从哪里开始。感谢您的所有帮助!
例如:
Dwelling1
user_id: 1
roomies: [1, 2, 3, 4]
其中 1、2、3、4 是 user_id。
更新模型
Dwelling Model
# 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 Model
# 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"
validates :first_name, presence: true, length: { maximum: 50 }
...
Updated Dwelling 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!"
redirect_to current_user
else
render 'new'
end
end
end
...
【问题讨论】:
-
非常感谢@MurifoX 清理我的问题格式!
标签: ruby-on-rails associations