Ruby on rails无法使用params创建

时间:2014-01-03 15:01:38

标签: ruby-on-rails form-submit

我有一个在Ruby上创建的rails。表单的代码如下所示:

<%= simple_form_for(@action) do |f|%>
    <%= render 'shared/error_messages' %>

    <%=f.label :action_name, "Action name"%>
    <%=f.text_field :action_name%></br>

    <%=f.input :startDate,:as => :datetime_picker, :label =>"Start date"%>
    <%=f.input :endDate,:as => :datetime_picker, :label =>"End date"%>

    <%=f.label :contentURL, "Content url"%>
    <%=f.text_field :contentURL%></br>
<%= f.button :submit, class: "btn btn-large btn-primary" %>

    <%end%>

但是当我点击提交按钮时,我收到此错误:

undefined method `permit' for "create":String

def action_params
    params.require(:action).permit(:action_name, :startDate,:endDate,:contentURL)

所有其他形式工作正常,我想这是非常明显的事情,只是看不到它:( 我非常感谢任何帮助,解决了这个问题。

谢谢!

编辑:

控制器代码:

def create
action = Action.new(action_params)
if @action.save
    flash[:success] = "New Action saved"
    redirect_to "/"
  else
    render 'new'
  end


 end

 private

 def action_params
     params.require(:action).permit(:action_name, :startDate,:endDate,:contentURL)
 end

1 个答案:

答案 0 :(得分:1)

在Rails 4中,您必须在控制器中使用强参数。 Here来自官方博客的一些解释。还有一些例子:

class PeopleController < ActionController::Base
  # This will raise an ActiveModel::ForbiddenAttributes exception because it's using mass assignment
  # without an explicit permit step.
  def create
    Person.create(params[:person])
  end

  # This will pass with flying colors as long as there's a person key in the parameters, otherwise
  # it'll raise a ActionController::MissingParameter exception, which will get caught by 
  # ActionController::Base and turned into that 400 Bad Request reply.
  def update
    redirect_to current_account.people.find(params[:id]).tap do |person|
      person.update_attributes!(person_params)
    end
  end

  private
    # Using a private method to encapsulate the permissible parameters is just a good pattern
    # since you'll be able to reuse the same permit list between create and update. Also, you
    # can specialize this method with per-user checking of permissible attributes.
    def person_params
      params.required(:person).permit(:name, :age)
    end
end

请注意,在private关键字的最后几行中,person_params方法是如何定义的,它声明了create允许的字段和更新方法。 。它是用于更新的person_params - 有效的例子 - 而不是原始的params数组。