所以我有一个具有博客模型和用户模型的应用程序。has_and_belongs_to_many关联混淆
现在用户可以订阅许多不同的博客,用户也可以创建他们自己的许多博客。
这个关联会是什么样子?
现在我的模型如下所示:
Blog.rb:
class Blog < ActiveRecord::Base
has_and_belongs_to_many :users
has_many :posts
end
User.rb:
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_and_belongs_to_many :blogs
validates :email, uniqueness: true, presence: true
validates_presence_of :password, on: :create
end
用户表中有一个blog_id:整型字段,并该博客有一个user_id:整数字段。
这是正确的吗?
命令如何工作? I.E:
u = User.last
b = u.blogs.build(title: "bla")
b.user (shows the owner of the blog)
b.users (shows the users that have subscribed to the blog)
最终,我想让用户订阅其他人的博客,并创建自己的博客。
你已经有了Rails 4风格和早期版本的混合。 'validates:password,presence:true,on::create'是可取的。 – tadman 2014-12-01 19:06:24