【发布时间】: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