【发布时间】:2012-03-25 14:32:59
【问题描述】:
我正在我的 Rails 3.2 应用程序上设置 has_many :through 关系。除了我不确定在创建关系时如何将值添加到连接表上的属性之外,我几乎可以正常工作。
以下是模型(注意 Checkins 表上的 source_id):
create_table "users", :force => true do |t|
t.integer "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "checkins", :force => true do |t|
t.integer "user_id"
t.integer "location_id"
t.integer "source_id"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
create_table "locations", :force => true do |t|
t.string "name"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
end
这是关系设置:
class User < ActiveRecord::Base
has_many :checkins
has_many :locations, :through => :checkins
end
class Location < ActiveRecord::Base
has_many :checkins
has_many :users, :through => :checkins
end
class Checkin < ActiveRecord::Base
belongs_to :location
belongs_to :user
end
我正在使用这些说明(本质上)加载用户和位置并创建与签入的关系:
source_id = 10
@user = User.first
@location = Location.first
@user.locations << @location
所以,我的问题是,当使用这一行时,如何将 source_id 值添加到 Checkins 表中:
@user.locations << @location
我也愿意接受关于创建具有这种关系的新用户签入的更好过程的建议,而不是我上面的建议(我已经看到了 create 和 build使用的方法,但似乎没有一个对我有用)
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-3 activerecord has-many-through