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
我需要执行哪些命令行来迁移以在User表和Post表之间执行这些不同的关系? 感谢
答案 0 :(得分:1)
Post
应 belong_to
:owner
,因为posts
表具有外键。此外,#users
的{{1}}有点过于模糊,而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
。事实上,你在技术上可以这样做,但是这样的模糊名称是不好的做法。