Rails数组参数未传递给数据库

时间:2016-09-23 18:36:21

标签: mysql ruby-on-rails forms

我试图将chosen-railsrails 4形式创建的字符串数组传递给mysql。但是,我得到的只是mysql中的空列或空列。任何建议都会很棒。

我的表单看起来如何(真实表单中的更多字段):

<%= form_for(@form) do |f| %>
<div class="col-md-12">
  <%= f.label "Cities", class: "input-desc" %><br>

  <div class="clearfix">
    <%= f.grouped_collection_select( :city_name, @state.order(:name), :cities, :name, :name, :name, { prompt: true }, { class: "form-control chosen-select", value: "Select Cities", multiple: true } )  %>
  </div>
</div>
<% end %>

模特:

class Form < ActiveRecord::Base
    has_many :city_names
    accepts_nested_attributes_for :city_names, allow_destroy: true, reject_if: :all_blank
end

控制器:

def create
  @form = Form.new(form_params)
  respond_to do |format|
    if @form.save
      city_names = params[:city_names]
      format.html { redirect_to form_url, notice: 'Form was successfully sent.' }
      format.json { render :show, status: :created, location: @form }
    else
      format.html { render :new }
      format.json { render json: @form.errors, status: :unprocessable_entity }
    end
  end
end

Private
def road_show_form_params
  params.require(:road_show_form).permit(:name, :adress, :phone, :email, :city_names, :comments, :paid)
end

SQL:

SQL (104.4ms)  INSERT INTO `forms` (`name`, `adress`, `phone`, `email`, `comments`, `paid`, `created_at`, `updated_at`) 
                            VALUES ('Corey Vincent', '', '1234567890', 'test@mail.com', '', 0, '2016-09-23 15:34:29', '2016-09-23 15:34:29')  

您可以看到SQL插入内容甚至不包含city_name参数。

但是你可以看到它被表格传递:

Parameters: {"utf8"=>"✓", 
"authenticity_token"=>"4ttP4U5+LXyrB8nQr2ka7rJqlk6cO+Fk5rCUMA2GWw2+Ww6QFf6DKW55uXVogfMkD0mvz/0QGJmw+42JQkZAZw==",
"form"=>{"paid"=>"false",
"name"=>"Corey Vincent",
"adress"=>"",
"phone"=>"1234567890",
"email"=>"test@mail.com",
"city_name"=>["", "Los Angeles", "Hartford"],
"comments"=>""},
"commit"=>"Submit Vote"}

1 个答案:

答案 0 :(得分:0)

我认为你的city_name参数被强大的参数阻挡了。通常情况下,使用nested_attributes时会出现类似情况:

<%= form_for @form do |f| %>
  ...
  <%= f.fields_for :city_names do |ff| %>
    ...
    <%= ff.grouped_collection_select(@state.order(:name), :cities, :name, :name, :name, { prompt: true }, { class: "form-control chosen-select", value: "Select Cities", multiple: true } )  %>
  <% end %>
  ...
<% end %>

然后,在你的控制器中:

private

  def road_show_form_params
    params.require(:road_show_form).permit(:name, :adress, :phone, :email, :comments, :paid, city_names_attributes: [:attr_1, :attr_2])
  end

city_names_attributes应该有一个与city_names表中的列对应的数组。在使用嵌套属性时,您基本上允许form对象为city_name对象获取一些参数并将其传递以保存在city_names表中。

另外,如果你查看你的参数,你会看到city_name,而road_show_form_params中你有city_names复数。最有可能的是,您的控制台输出中会有unpermitted parameter

这就是假设您尝试将city_names保存到自己的表格中。