将模型与多态相关联
我试图将联系人与类关联起来,但作为两种不同的类型。 Current_classes 和 Interested_classes。
我知道我需要启用多态,但我不确定需要在哪里启用它。
这就是我现在所拥有的
class CreateClasses < ActiveRecord::Migration
def self.up
create_table :classes do |t|
t.string :class_type
t.string :class_name
t.string :date
t.timestamps
end
end
def self.down
drop_table :classes
end
end
class CreateContactsInterestedClassesJoin < ActiveRecord::Migration
def self.up
create_table 'contacts_interested_classes', :id => false do |t|
t.column 'class_id', :integer
t.column 'contact_id', :integer
end
end
def self.down
drop_table 'contacts_interested_classes'
end
end
class CreateContactsCurrentClassesJoin < ActiveRecord::Migration
def self.up
create_table 'contacts_current_classes', :id => false do |t|
t.column 'class_id', :integer
t.column 'contact_id', :integer
end
end
def self.down
drop_table 'contacts_current_classes'
end
end
然后在我的联系人模型中我想要有这样的东西。
class Contact < ActiveRecord::Base
has_and_belongs_to_many :classes, :join_table => "contacts_interested_classes", :foreign_key => "class_id" :as => 'interested_classes'
has_and_belongs_to_many :classes, :join_table => "contacts_current_classes", :foreign_key => "class_id" :as => 'current_classes'
end
我做错了什么?
I am trying to associate Contacts with Classes but as two different types. Current_classes and Interested_classes.
I know I need to enable polymorphic but I am not sure as to where it needs to be enabled.
This is what I have at the moment
class CreateClasses < ActiveRecord::Migration
def self.up
create_table :classes do |t|
t.string :class_type
t.string :class_name
t.string :date
t.timestamps
end
end
def self.down
drop_table :classes
end
end
class CreateContactsInterestedClassesJoin < ActiveRecord::Migration
def self.up
create_table 'contacts_interested_classes', :id => false do |t|
t.column 'class_id', :integer
t.column 'contact_id', :integer
end
end
def self.down
drop_table 'contacts_interested_classes'
end
end
class CreateContactsCurrentClassesJoin < ActiveRecord::Migration
def self.up
create_table 'contacts_current_classes', :id => false do |t|
t.column 'class_id', :integer
t.column 'contact_id', :integer
end
end
def self.down
drop_table 'contacts_current_classes'
end
end
And then inside of my Contacts Model I want to have something like this.
class Contact < ActiveRecord::Base
has_and_belongs_to_many :classes, :join_table => "contacts_interested_classes", :foreign_key => "class_id" :as => 'interested_classes'
has_and_belongs_to_many :classes, :join_table => "contacts_current_classes", :foreign_key => "class_id" :as => 'current_classes'
end
What am I doing wrong?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我可以给你答案,但你最好阅读这篇文章 rails 指南中的多态关联
I can give u the answer but better you read this post Polymorphic Associations from rails guide