繁体   English   中英

Ruby on Rails无法使用params创建

[英]Ruby on rails can't create with params

我在Ruby on Rails中创建了一个from。 表单的代码如下所示:

<%= 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

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

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

请注意,在最后person_params行中,如何在private关键字下定义person_params方法,该方法在顶部声明将由create和update方法分配的允许字段。 这是用于更新的person_params (有效示例),而不是原始的params数组。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM