起初,当我创建帖子时,用户id为nil。最初我的post_params只是:content&:类别直到我添加了:user_id,我才终于能够让post.user.first_name正常工作。(first_name是一个User列)我在这方面做了很多工作,有一次在创建帖子时,id会显示出来,但在刷新页面时,id就会消失(我使用ajax在提交后显示帖子)。params仍然不包括:user_id,但现在当post被创建并放入db时,user_id就在那里。我没有明确说明user_id是什么,那么它怎么知道呢?来自before_authentication!从设计中筛选?还是从current_user.posts.create获取id?
最初有
def create
@post=post.create({content: post_params[:content], category: post_params[:category].downcase})
end
然后。。。
def create
@post = current_user.posts.create({content: post_params[:content], category: post_params[:category].downcase})
end
private
def post_params
params.require(:post).permit(:content, :category, :user_id)
end
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = 6 ORDER BY "users"."id" ASC LIMIT 1
(0.1ms) begin transaction
SQL (0.3ms) INSERT INTO "posts" ("category", "content", "created_at", "updated_at", "user_id") VALUES (?, ?, ?, ?, ?) [["category", "announcements"], ["content", "Hi All!"], ["created_at", "2014-10-13 19:58:02.937604"], ["updated_at", "2014-10-13 19:58:02.937604"], ["user_id", 6]]
(3.8ms) commit transaction
Like Exists (0.2ms) SELECT 1 AS one FROM "likes" WHERE "likes"."user_id" = 6 AND "likes"."post_id" = 69 LIMIT 1
当您调用create或build-on-a relationship(在本例中为posts of user)时,Rails会自动设置良好关系字段,将对象链接到父对象。