2013-03-04 36 views
1

我有以下的用户和帖子的关系:如何通过用户创建新帖子?

class User < ActiveRecord::Base 
    attr_accessible :email, :password, :password_confirmation 

    has_many :posts 
end 


class Post < ActiveRecord::Base 
    attr_accessible :content 

    belongs_to :user 
end 

我想通过一个用户创建一个新的职位,但我得到一个错误。我不知道为什么:

1.9.3-p392 :001 > @user = User.where(:id => 1) 
    User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = 1 
=> [#<User id: 1, email: "[email protected]", encrypted_password: "$2a$10$ltpBpN0gMzOGULVtMxqgueQHat1DLkY.Ino3E1QoO2nI...", reset_password_token: nil, reset_password_sent_at: nil, remember_created_at: nil, sign_in_count: 6, current_sign_in_at: "2013-03-04 05:33:46", last_sign_in_at: "2013-03-03 22:18:17", current_sign_in_ip: "127.0.0.1", last_sign_in_ip: "127.0.0.1", created_at: "2013-03-02 03:41:48", updated_at: "2013-03-04 05:33:46", avatar_file_name: nil, avatar_content_type: nil, avatar_file_size: nil, avatar_updated_at: nil>] 
1.9.3-p392 :002 > @user.posts.create(:content => "This is the content") 
NoMethodError: undefined method `posts' for #<ActiveRecord::Relation:0x000000024ca868> 
+0

使用'@user = User.where(:ID => 1).first' – jvnill 2013-03-04 08:44:11

+0

尝试使用@user = user.find_by_id( 1) – 2013-03-04 09:30:01

回答

0

您的代码

User.where(:id => 1) 

不给你一个模型实例,但relation。因此ActiveRecord上的NoMethodError :: 关系

你的第一个行更改为

User.find(1) 

和你的罚款。

+0

就是这样! 5分钟后我会接受。 – egidra 2013-03-04 08:47:37

+0

请参阅我的修订答案:除User.find ...之外,不要使用'User.where ...' – awendt 2013-03-04 08:48:28

2

ActiveRecord Relationships中的wherefind之间有区别。

查询:

@user = User.where(:id => 1)是给你的阵列哈希值。

因此,当您对上述查询执行类似@user.posts的操作时,由于没有与此散列关联的此类帖子,因此会给出NoMethodError on ActiveRecord::Relation的错误。因此,为了将其转换成id为1的用户,你这样做:

@user = User.where(:id => 1).first 

@user = User.find(:id => 1) 

都将给你一个ID为1(只有一条记录)的用户和那么你可以使用这个:

@user.posts 

以上将给用户的相关联的帖子ID为1

然后你可以这样做:

@user.posts.create(:content => "Post of user 1") 

那么你正在尝试做的实际上是给你的哈希(组用户),但实际上,你只需要一个用户创建相关的职位。

另外,请参阅difference between find and where

0

使用此

@user = User.where(:id => 1).shift 
@user.posts.create(:content => "This is the content") 

OR

@user = User.find(1) 
@user.posts.create(:content => "This is the content")