【发布时间】:2014-11-16 07:31:05
【问题描述】:
我创建了一个表单来向属于:article 模型的:vote 模型添加一条记录。如下所示,创建:vote 记录的表单位于:article 视图中。在不为这些模型使用嵌套路由时,我没有使用form_for 助手,而是使用普通的form_tags。我的问题是strong_parameters 不允许我的隐藏字段通过。
<p id="notice"><%= notice %></p>
<p>
<strong>Title:</strong>
<%= @article.title %>
</p>
<p>
<strong>Body:</strong>
<%= @article.body %>
</p>
<p>
<strong>User:</strong>
<%= @article.user_id %>
</p>
<%= form_tag("/vote/#{@article.id}", method: :post) do -%>
<%= hidden_field_tag 'vote[value]', 1 %>
<%= submit_tag 'Up vote' %>
<% end -%>
<%= link_to 'Edit', edit_article_path(@article) %>
<%= link_to 'Back', articles_path %>
正如您在控制器代码中看到的那样,我已将参数列入白名单,日志数据显示帖子正文以正确的格式用于参数哈希,但它不会达到我的创建操作。
class VotesController < ApplicationController
def create
@article = Article.find(params[:id])
@vote = Vote.new(params[:strong_vote])
@vote.user_id = current_user.id
@vote.article_id = @article.id
@vote.save
redirect_to @article
end
private
def strong_vote
params.require(:vote).permit(:value)
end
end
Processing by VotesController#create as HTML Parameters:{"utf8"=>"✓","authenticity_token"=>"Y6eBxpwGXGdT2toeUrxAlLW58Hj8Eux+SvoWeVUoYa8=","vote"=>{"value"=>"1"}, "commit"=>"Up vote","id"=>"7"}
Article Load (0.1ms) SELECT "articles".* FROM "articles" WHERE "articles"."id" = ? LIMIT 1 [["id", 7]]
User Load (0.1ms) SELECT "users".* FROM "users" WHERE"users"."id" = 1 ORDER BY "users"."id" ASC LIMIT 1
Rendered text template (0.0ms)
Completed 200 OK in 7ms (Views: 1.0ms | ActiveRecord: 0.4ms)
这是我的路线,以防万一。
devise_for :users
root 'articles#index'
resources :articles
post '/vote/:id' => 'votes#create'
更新:我试过你的回答 doz87 但我收到以下错误:
ArgumentError in VotesController#create
When assigning attributes, you must pass a hash as an argument.
Extracted source (around line #5):
3
4
5
6
7
8
def create
@article = Article.find(params[:id])
@vote = Vote.new(:strong_vote)
@vote.user_id = current_user.id
@vote.article_id = @article.id
@vote.save
Rails.root: /home/w/Folders/playground/ruby/voter
Application Trace | Framework Trace | Full Trace
app/controllers/votes_controller.rb:5:in `create'
Request
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"AVKHgcsOwQhwWJGfSGQhIL1Lbr7yhSRaGKTrxuLcAuo=",
"vote"=>{"value"=>"1"},
"commit"=>"Up vote",
"id"=>"7"}
【问题讨论】:
-
是的,您将符号传递给需要哈希的 Vote.new 语句。如果您使用不带冒号的 strong_vote,那么您将传入您在控制器中定义的参数哈希。
标签: ruby-on-rails-4 strong-parameters actioncontroller