rails如何解释params hash,严格的参数

时间:2014-10-13 21:10:39

标签: ruby-on-rails ruby-on-rails-4 params strong-parameters

首先,当我创建帖子时,用户ID为零。最初我的post_params只是:content& :类别。直到我添加:user_id,我终于能够使post.user.first_name正常工作了。(first_name是一个用户专栏)我用它搞砸了很多,当我创建帖子的时候,id会显示,但随后刷新页面时,id会消失(我在提交后使用ajax显示帖子)。参数仍然不包括:user_id,但现在当创建帖子并将其放入数据库时​​,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

1 个答案:

答案 0 :(得分:0)

当您在关系上调用create或build(在这种情况下是用户的帖子)时,Rails会自动实例化良好的关系字段以将对象链接到父级。