我有以下的用户和帖子的关系:如何通过用户创建新帖子?
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>
使用'@user = User.where(:ID => 1).first' – jvnill 2013-03-04 08:44:11
尝试使用@user = user.find_by_id( 1) – 2013-03-04 09:30:01