【发布时间】:2013-12-05 16:31:47
【问题描述】:
我的目标是让用户能够提名来宾谈论一个主题,但复杂的是他们(或用户)可以提供许多“链接”来支持这种选择来提名来宾。
所以我的表格最简单的形式如下所示:
create_table "topics", force: true do |t|
t.string "name"
end
create_table "guests", force: true do |t|
t.string "name"
end
create_table "topic_guests", force: true do |t|
t.integer "topic_id"
t.integer "guest_id"
t.integer "user_id" #(who nominated this guest)
end
create_table "links", force: true do |t|
t.integer "user_id"
t.integer "topic_id"
t.integer "guest_id"
t.string "url"
end
我很难让链接与 has_many :through 一起使用,因为 :through 是另一个 has_many :through (whew) 的连接表。
主题和来宾的添加非常适合此配置:
class Topic < ActiveRecord::Base
belongs_to :user
has_many :topic_guests, :dependent => :destroy
has_many :guests, :through => :topic_guests
end
class Guest < ActiveRecord::Base
has_many :topic_guests, :dependent => :destroy
has_many :topics, :through => :topic_guests
end
在为被提名的客人添加链接时,链接模型很简单:
class Link < ActiveRecord::Base
belongs_to :guest
belongs_to :topic
belongs_to :user
end
但我似乎无法添加指向指定客人的链接。目标是做这样的事情(输入这个让我意识到为什么这是一项以“rails 方式”完成的艰巨任务)
@topic.guests.find(params[:guest_id]).links << current_user.links.build(link_params)
【问题讨论】:
标签: activerecord ruby-on-rails-4 has-many-through