简体   繁体   English

Rails如何解释参数哈希,严格参数

[英]How rails interprets params hash, strict parameters

At first, when I was creating posts, the user id was nil. 最初,当我创建帖子时,用户ID为nil。 Originally my post_params were just :content & :category. 最初,我的post_params只是:content和:category。 It wasn't until I added :user_id that I was finally able to get post.user.first_name to work properly.(first_name is a User column) I screwed around a lot with it and at one point when I was creating posts, the id would show up, but then on a refresh of the page, the id would disappear(I am using ajax to show the post after submit). 直到我添加了:user_id,我终于能够使post.user.first_name正常工作。(first_name是一个User列)我在这上面花了很多时间,在创建帖子时, id将显示,但是在刷新页面后,id将消失(提交后,我使用ajax显示帖子)。 The params still do not include :user_id, but now when the post is created and put into the db, the user_id is there. 这些参数仍然不包括:user_id,但是现在创建帖子并将其放入db后,user_id就在那里了。 I am not explicitly saying what the user_id is, so how does it know? 我没有明确说出user_id是什么,那么它怎么知道? from the before_authentication! 来自before_authentication! filter from devise? 从设计中过滤? Or does it get the id from current_user.posts.create? 还是从current_user.posts.create获取ID?

Originally had 本来有

def  create  
@post=post.create({content: post_params[:content], category:   post_params[:category].downcase})
end

then... 然后...

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时(在这种情况下为用户的职位),Rails会自动实例化良好的关系字段以将对象链接到父对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM