class Post < ActiveRecord::Base
has_one :owner, class_name: "User", foreign_key: "owner_id" #creator post
has_many :users #followers post
end
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :posts
end为了在用户表和Post表之间执行这些不同的关系,我需要执行哪些命令行来迁移?谢谢
发布于 2016-02-17 21:55:44
belong_to:owner,应该是Post,因为posts表有外键。而且,它的#users和User#posts的名字有点太模糊了。
这是你们的模特:
class Post < ActiveRecord::Base
belongs_to :owner, class_name: 'User', inverse_of: :owned_posts # foreign_key: :owner_id will be inferred
has_many :subscriptions
has_many :followers, through: :subscriptions, source: :user, class_name: 'User', inverse_of: :followed_posts
end
class Subscription < ActiveRecord::Base
belongs_to :post
belongs_to :user
end
class User < ActiveRecord::Base
has_many :owned_posts, class_name: 'Post', inverse_of: :owner
has_many :subscriptions
has_many :followed_posts, through: :subscriptions, source: :post, class_name: 'Post', inverse_of: :followers
end以下是支持他们的迁徙:
class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
# ...
end
end
end
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.integer :owner_id
# ...
end
end
end
class CreateSubscriptions < ActiveRecord::Migration
def change
create_table :subscriptions do |t|
t.integer :post_id
t.integer :user_id
end
end
end如果不是因为“所有权”关系,那么可以使用has_and_belongs_to_many关系:
subscriptions迁移重命名为posts_users (必须按字母顺序为复数),Post.has_and_belongs_to_many :users和User.has_and_belongs_to_many :posts。实际上,从技术上讲,您可以做到这一点,但是使用这样的模糊名称是一种糟糕的做法。
https://stackoverflow.com/questions/35466451
复制相似问题