Rails强大的参数无法识别我的参数

时间:2014-11-16 07:31:06

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

我创建了一个表单,以便将记录添加到属于:vote模型的:article模型中。如下所示,创建: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"}

1 个答案:

答案 0 :(得分:1)

这不起作用的原因是你没有为新投票分配任何东西。 Params [:strong_vote]不存在

@vote = Vote.new(params[:strong_vote])

你应该这样写:

@vote = Vote.new(strong_vote)

从失败的保存中捕获任何错误也是一种很好的做法。如果出现问题,你应该将@ vote.save包装在if块中。

if @vote.save
redirect_to @article
else
flash.now[:notice] = "Something went wrong while saving"
render 'new'
end