您可以使用
@user = User.find(1)
@post = @user.posts.build(posts_attributes_as_hash)
@post.save
甚至
post = Post.new(posts_attributes)
@user = User.find(1)
@user.posts << post
编辑
要使用直接创建:
@user = User.find(1)
@post = @user.posts.create(posts_attributes_as_hash)
欲了解更多信息,看看has_many-association-referenceË特别是在部分称为4.3.1 Methods Added by has_many
新编辑:
我创建了一个新的项目,你的代码,并在铁轨控制台我想下面的命令
User.create(:username => "UserNamedTest", :email => "[email protected]")
SQL (13.6ms) INSERT INTO "users" ("created_at", "email", "password_hash", "password_salt", "updated_at", "username") VALUES (?, ?, ?, ?, ?, ?) [["created_at", Wed, 14 Dec 2011 09:02:46 UTC +00:00], ["email", "[email protected]"], ["password_hash", nil], ["password_salt", nil], ["updated_at", Wed, 14 Dec 2011 01:03:26 UTC +00:00], ["username", "UserNamedTest"]]
=> #<User id: 2, username: "UserNamedTest", email: "[email protected]", password_hash: nil, password_salt: nil, created_at: "2011-12-14 09:02:46", updated_at: "2011-12-14 09:02:46">
user = User.find_by_username("UserNamedTest")
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."username" = 'UserNamedTest' LIMIT 1
=> #<User id: 2, username: "UserNamedTest", email: "[email protected]", password_hash: nil, password_salt: nil, created_at: "2011-12-14 09:02:46", updated_at: "2011-12-14 09:02:46">
new_post = user.posts.create(:title => "just a test", :body =>"body of article test")
SQL (0.5ms) INSERT INTO "posts" ("body", "created_at", "title", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?) [["body", "body of article test"], ["created_at", Wed, 14 Dec 2011 09:03:59 UTC +00:00], ["title", "just a test"], ["updated_at", Wed, 14 Dec 2011 09:03:59 UTC +00:00], ["user_id", 2]]
=> #<Post id: 2, title: "just a test", body: "body of article test", user_id: 2, created_at: "2011-12-14 09:03:59", updated_at: "2011-12-14 09:03:59">
irb(main):022:0> new_post.inspect
=> "#<Post id: 2, title: \"just a test\", body: \"body of article test\", user_id: 2, created_at: \"2011-12-14 09:03:59\", updated_at: \"2011-12-14 09:03:59\">"
从我看到的代码是确定的,在后创建没有错误
尝试更改为的has_many:帖子,CLASS_NAME => “邮报”,:foreign_key => “USER_ID”:依赖=> “消灭”和belongs_to的:用户:CLASS_NAME =>用户,:foreign_key => “user_id”。有时候,ActiveRecord可能有点怪异。不要忘记重新启动服务器 – Hishalv 2011-12-14 08:44:48
你确定'user_id`列存在于`posts`表中吗? – Mischa 2011-12-14 08:50:31