Ruby on rails 通过与桥接表中的其他列关联
我有两个表,course和category,还有一个带有course_id和category_id的桥接表categories。我在表category_rank中添加了一个额外的列,该列是一个整数,用于根据用户偏好对类别进行排序。我正在努力在数据库中创建条目。这是我的桌子:Ruby on rails 通过与桥接表中的其他列关联,ruby-on-rails,ruby,ruby-on-rails-4,Ruby On Rails,Ruby,Ruby On Rails 4,我有两个表,course和category,还有一个带有course_id和category_id的桥接表categories。我在表category_rank中添加了一个额外的列,该列是一个整数,用于根据用户偏好对类别进行排序。我正在努力在数据库中创建条目。这是我的桌子: create_table "categories", force: true do |t| t.string "name" t.boolean "is_active", default: true
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
@course.categories您可以访问以下额外属性:
@course.categorisations.first.rank
我建议您为联接表创建一个新实例-分类
@c = Categorisation.find_or_create_by(<course and category>)
@c.rank = <assign rank>
@c.save!
@c=categorization.find_或_create_by()
@c、 排名=
@c、 救命!
问题不在于访问附加属性。关于添加附加属性值,但架构中已添加了类别_秩
。我向他展示了如何通过分类协会访问它。。他可以给它任意赋值。是的,但是如果课程/类别不存在,它会创建记录吗。。。有道理。。。不知道从什么时候开始我会在Rails中感到舒适…-)我是否需要先将课程保存到数据库中,然后才能执行此实例化看起来有点混乱,必须对数据库进行两次不同的保存,感觉rails应该能够处理这些问题it@Andrew_tainton我想你也可以这样做@c=categorization.new(课程:@course,category:@category,category\u rank:category\u rank)
然后c.保存代码>。