【问题标题】:Adding attribute values to a join table record in a has_many :through association upon creation将属性值添加到 has_many 中的连接表记录:通过创建时的关联
【发布时间】: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

我也愿意接受关于创建具有这种关系的新用户签入的更好过程的建议,而不是我上面的建议(我已经看到了 createbuild使用的方法,但似乎没有一个对我有用)

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 activerecord has-many-through


    【解决方案1】:

    直接创建Checkin对象。

    checkin = Checkin.new user: @user, location: @location, source_id: source_id 
    checkin.save
    

    【讨论】:

    • 效果很好。您能否指导我查看一份详细说明 has_many :through 关联的操作(或只是基本 CRUD)的文档?我找到的 Rails 指南告诉你如何设置它,但不是真正要使用的 CRUD 方法。
    • @wrburgess 你有没有找到一个资源来解释 has_many :through 关联的 CRUD?
    猜你喜欢
    • 1970-01-01
    • 2016-08-20
    • 2011-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-25
    • 1970-01-01
    相关资源
    最近更新 更多