Ruby on rails 如何通过用户创建新帖子?

Ruby on rails 如何通过用户创建新帖子?,ruby-on-rails,ruby-on-rails-3,Ruby On Rails,Ruby On Rails 3,我有以下用户和帖子关系: 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 我试图通过一个用户创建一个新帖子,但是我得到了一个错误。我不

我有以下用户和帖子关系:

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: "test@test.com", 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>
你的代码

User.where:id=>1 不提供模型实例,但提供一个。因此,ActiveRecord::Relation上出现了NoMethodError

将第一行更改为

User.find(1)

您很好。

在ActiveRecord关系中的where和find之间存在差异

查询:

@user=user。其中:id=>1为您的数组提供哈希值

因此,当您对上述查询执行@user.posts之类的操作时,它会在ActiveRecord::Relation上给出NoMethodError错误,因为没有与此哈希关联的此类post。因此,要将其转换为id为1的用户,请执行以下操作:

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

两者都将只为id为1的用户提供一条记录,然后您可以使用此记录:

@user.posts
上面将给出id为1的用户的相关帖子

然后你可以做:

@user.posts.create(:content => "Post of user 1")
因此,您试图做的实际上是给您用户的散列集,但实际上您只希望一个用户创建相关的帖子

另外,请参见。

使用此

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


使用@user=user.where:id=>1.firsttry使用@user=user.find_by_id1请查看我的修订答案:不使用user.where。。。除了用户之外,其他都有。查找。。。
@user = User.where(:id => 1).shift
@user.posts.create(:content => "This is the content")
@user = User.find(1)
@user.posts.create(:content => "This is the content")