【问题标题】:has_many through association with additional column in the bridging tablehas_many 通过与桥接表中的附加列关联
【发布时间】:2014-05-06 09:57:24
【问题描述】:

我有两个表,课程和类别,并且我有一个带有 course_id 和 category_id 的桥接表分类。我在表 category_rank 中添加了一个附加列,它是一个整数,用于根据用户偏好对类别进行排名。我正在努力在数据库中创建条目。这是我的表格:

  create_table "categories", force: true do |t|
    t.string   "name"
    t.boolean  "is_active",  default: true
    t.datetime "created_at"
    t.datetime "updated_at"
  end

  create_table "categorisations", force: true do |t|
    t.integer  "category_id"
    t.integer  "course_id"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "category_rank"
  end


create_table "courses", force: true do |t|
    t.string   "title"
    t.datetime "start_date"
    t.string   "duration"
    t.boolean  "is_active",                     default: true
    t.integer  "state"
    t.integer  "partner_id"
    t.integer  "user_id"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "photo"
    t.integer  "partner"
    t.boolean  "is_published",                  default: false    
  end

这是模型

class Course < ActiveRecord::Base
  has_many :categorisations
  has_many :categories, :through=> :categorisations 
  belongs_to :partner
end
class Category < ActiveRecord::Base
  has_many :categorisations 
  has_many :courses, :through=> :categorisations
  belongs_to :user
end
class Categorisation < ActiveRecord::Base
  belongs_to :category
  belongs_to :course
end

当我创建课程时,我使用了一个类别对象列表,这很好用

@course.categories << @categories

但我现在需要为桥接表中的每个类别添加一个排名

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4


    【解决方案1】:

    我建议您为连接表创建一个新实例 - 分类。

    @c = Categorisation.find_or_create_by(<course and category>)
    @c.rank = <assign rank>
    @c.save!
    

    【讨论】:

    • 是的,但是如果课程/类别不存在,它会创建记录吗?
    • 嗯...有道理...不知道从什么时候开始我会在 Rails 中感到舒适.. :-)
    • 是否需要先将课程保存到数据库中才能进行实例化
    • 看起来有点乱,必须对数据库进行两次不同的保存,感觉应该是rails应该处理它
    • @Andrew_tainton 我想你也可以这样做@c = Categorisation.new(course: @course,category: @category,category_rank: category_rank) 然后c.save!
    【解决方案2】:

    您可以像这样访问额外的属性:

    @course.categorisations.first.rank
    

    【讨论】:

    • 问题不在于访问附加属性。它关于添加附加属性值
    • category_rank 已经添加到架构中。我向他展示了如何通过分类关联访问它。他可以为它分配任意值。
    猜你喜欢
    • 2012-01-11
    • 2015-08-22
    • 2012-07-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多