如何告知has_many :through
和/或foreign_key
使用哪个class
关联?
我已尝试过上述的每一种排列,通常会收到:NoMethodError: undefined method 'relation_delegate_class' for "User":String
ActiveRecord::Schema.define(version: 20141031013511) do
create_table "messages", force: true do |t|
t.string "content"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "creator_id"
end
create_table "messages_views", force: true do |t|
t.integer "message_viewed"
t.integer "message_viewer"
end
create_table "shows_viewers", force: true do |t|
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", force: true do |t|
t.string "username"
t.datetime "created_at"
t.datetime "updated_at"
end
end
class MessagesView < ActiveRecord::Base
belongs_to :message_viewed
belongs_to :message_viewer
end
class Message < ActiveRecord::Base
belongs_to :creator, class_name: 'User'
has_many :messages_views
has_many :message_viewers, through: :messages_views, class: 'User', foreign_key: 'message_viewer'
end
class User < ActiveRecord::Base
has_many :messages, foreign_key: 'creator_id'
has_many :messages_views
has_many :message_vieweds, through: :messages_views, class: 'Message', foreign_key: 'message_viewed'
end
This是该应用的当前状态。
答案 0 :(得分:3)
我认为关联表和你的代码的问题应该是这样的:
class MessagesView < ActiveRecord::Base
belongs_to :message_viewed, class_name: 'Message'
belongs_to :message_viewer, class_name: 'User'
end
class Message < ActiveRecord::Base
belongs_to :creator, class_name: 'User'
has_many :messages_views, foreign_key: 'message_viewed', class_name: "messages_view"
has_many :message_viewers, through: :messages_views, class_name: 'User', foreign_key: 'message_viewer'
end
class User < ActiveRecord::Base
has_many :messages, foreign_key: 'creator_id'
has_many :messages_views, foreign_key: 'message_viewer', class_name: "messages_view"
has_many :message_vieweds, through: :messages_views, class_name: 'Message', foreign_key: 'message_viewed'
end