undefined方法`stringify_keys'for“create”:再次在rails上的ruby中的字符串

时间:2012-10-29 09:12:57

标签: ruby-on-rails ruby ruby-on-rails-3

我收到错误

Started POST "/actions" for 127.0.0.1 at 2012-10-29 15:04:01 +0600
Processing by ActionsController#create as HTML
  Parameters: {"utf8"=>"✓", "authenticity_token"=>"lfHYF3EQn1/lMReK3alX3NsGa4wSMejC/0fEeoAFYUY=", "commit"=>"Create Action"}
Completed 500 Internal Server Error in 1ms

NoMethodError (undefined method `stringify_keys' for "create":String):
  app/controllers/actions_controller.rb:43:in `new'
  app/controllers/actions_controller.rb:43:in `create'

此代码完全由Rails生成,我不明白为什么它不起作用

这是模型

class Action < ActiveRecord::Base
  attr_accessible :name, :user_id
end

这是控制器部分

# GET /actions/new
# GET /actions/new.json
def new
  @action = Action.new

  respond_to do |format|
    format.html # new.html.erb
    format.json { render json: @action }
  end
end

def create
  @action = Action.new(params[:action]) # here we get an error !

  respond_to do |format|
    if @action.save
      format.html { redirect_to @action, notice: 'Action was successfully created.' }
      format.json { render json: @action, status: :created, location: @action }
    else
      format.html { render action: "new" }
      format.json { render json: @action.errors, status: :unprocessable_entity }
    end
  end
end

这是表单代码

<%= form_for(@action) do |f| %>
  <% if @action.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@action.errors.count, "error") %> prohibited this action from being saved:</h2>

      <ul>
      <% @action.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :name %><br />
    <%= f.text_field :name %>
  </div>
  <div class="field">
    <%= f.label :user_id %><br />
    <%= f.number_field :user_id %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

当我按帖子时,firebug会显示此请求参数

utf8:✓
authenticity_token:lfHYF3EQn1/lMReK3alX3NsGa4wSMejC/0fEeoAFYUY=
action[name]:sdf
action[user_id]:23
commit:Create Action

如果我理解正确,这必须工作,rails必须将action [name]和action [user_id]转换为哈希表并将其放入参数[:action],然后Action.new将此哈希表作为参数。有什么问题?

2 个答案:

答案 0 :(得分:4)

啊,我知道。你有一个名字冲突。

action是保留名称。与controllerid以及其他人一起。为表单使用其他名称。

当您发布到/actions/create时,params[:controller]应该是'帖子'而params[:action]应该是'创建'。这些参数由Rails指定。

答案 1 :(得分:0)

在你的参数中你得到params [:controller] = controller_name和params [:action] = action_name
在您的情况下,您正在从action_name创建Action abject而不是对象操作的params。尝试在params中使用不同的名称作为对象参数。