【问题标题】:How rails interprets params hash, strict parametersrails 如何解释 params 哈希、严格参数
【发布时间】:2014-10-13 21:10:38
【问题描述】:

起初,当我创建帖子时,用户 ID 为 nil。最初我的 post_params 只是 :content & :category。直到我添加 :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

【问题讨论】:

  • 你需要学习一点。 post_params 是一组允许的参数,并按原样使用。 current_user.posts.create(post_params)... 这会将提交给数据库引擎的参数限制为在def post_params 中定义的参数以及单独的参数...

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-10-01
    • 1970-01-01
    • 2019-03-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-12-13
    • 1970-01-01
    相关资源
    最近更新 更多