Ran*_*ess 2 ruby activerecord ruby-on-rails has-many-through ruby-on-rails-3
我在我的Rails 3.2应用程序上建立了一个has_many:through关系.我有大多数工作,除了我不确定如何在创建关系时为连接表上的属性添加值.
下面是模型(注意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
Run Code Online (Sandbox Code Playgroud)
这是关系设置:
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
Run Code Online (Sandbox Code Playgroud)
我正在使用这些指令(实质上)来加载用户和位置并与Checkin建立关系:
source_id = 10
@user = User.first
@location = Location.first
@user.locations << @location
Run Code Online (Sandbox Code Playgroud)
所以,我的问题是,如何在使用此行时向checkins表添加source_id值:
@user.locations << @location
Run Code Online (Sandbox Code Playgroud)
我也愿意接受关于使用这种关系创建新用户签到的更好过程的建议,而不是我上面提到的(我看过使用的创建和构建方法,但似乎没有一个对我有用)
Checkin直接创建对象.
checkin = Checkin.new user: @user, location: @location, source_id: source_id
checkin.save
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3951 次 |
| 最近记录: |