[英]Rails: How to set up Active Record Associations?
I am relatively new to rails and doing the simplest thing: Associate users and posts. 我对Rails比较陌生,并且做的最简单:关联用户和帖子。 I read this , but what more than this do I need to do to make it work (or is this the only thing)?:
我读过这篇文章 ,但是要使它正常工作(或者这是唯一的事情),我还需要做些什么?
class User < ActiveRecord::Base
has_many :posts, :dependent => :destroy
end
class Post < ActiveRecord::Base
belongs_to :user
end
Update: I can't make it work. 更新:我无法使其正常工作。 When I make a post with a signed in user, I get false when I do
@user.posts.any?
当我使用已登录的用户发布帖子时,我执行
@user.posts.any?
时会@user.posts.any?
in the console. 在控制台中。 My code:
我的代码:
post.rb post.rb
class Post < ActiveRecord::Base
attr_accessible :title, :user_id
belongs_to :user
before_create :default_values
user.rb (I use devise) user.rb(我使用devise)
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
attr_accessible :email, :password, :password_confirmation, :remember_me
has_many :posts, dependent: :destroy
end
20130320162700_create_posts.rb 20130320162700_create_posts.rb
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :title
t.integer :user_id
t.timestamps
end
end
end
You should make sure to include User's id in the migration that creates the posts table. 您应该确保在创建posts表的迁移中包括用户ID。 In your migration file (in the db/migrate folder you will find a file named like 20130325105934_create_posts.rb)
在您的迁移文件中(在db / migrate文件夹中,您将找到一个名为20130325105934_create_posts.rb的文件)
Inside the file you will find the migration code. 在文件中,您将找到迁移代码。 Along the other declared attributes add
连同其他声明的属性一起添加
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
......
t.integer :user_id
......
end
end 结束
It should be enough to make things roll :-) 它应该足以使事情滚动:-)
Inside your code then you can create a new user as 在您的代码内,然后您可以创建一个新用户
@user = User.new(:login => "my_user", .....)
and then add posts with one of these two ways (there are others two). 然后使用以下两种方法之一添加帖子(还有其他两种方法)。
post = Post.new(:title => "something", :text => "more of something", :user_id = @user.id)
or 要么
post = Post.new(:title => "something", :text => "more of something")
@user.posts << post
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.