rails 4多种形式的保存和更新

时间:2014-01-31 06:26:42

标签: ruby-on-rails forms many-to-many

我有多对多的关系,我想使用复选框来选择我需要的关系。 控制器(我使用脚手架)

...
  def update
    #params[:characteristic][:property_ids] ||= []
    respond_to do |format|
      if @characteristic.update(characteristic_params)
        format.html { redirect_to @characteristic, notice: 'Characteristic was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: 'edit' }
        format.json { render json: @characteristic.errors, status: :unprocessable_entity }
      end
    end
  end
...
    def characteristic_params
      params[:characteristic][:property_ids] ||= []
      params.require(:characteristic).permit(:characteristicable_id, :characteristicable_type, :property_ids)

    end

模型

class Property < ActiveRecord::Base
  has_and_belongs_to_many :characteristics
  mount_uploader :image, PropertyUploader
end

class Characteristic < ActiveRecord::Base
   has_and_belongs_to_many :properties
end

我的特色形式

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

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

  <% end %>

    <% for  p in Property.find(:all) %>
        <p>
        <%= check_box_tag "characteristic[:property_ids][]", p.id, @characteristic.properties.include?(p)  %>
        <%= image_tag p.image_url(:thumb).to_s %>
        <%= p.name %>
        </p>
    <% end %>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

当我选择复选框并保存我的关系时不保存,但通知说更新\保存是成功的。如果我没有选中任何复选框,则会出现错误

undefined method `[]' for nil:NilClass
params[:characteristic][:property_ids] ||= []

解决

<%= check_box_tag "characteristic[:property_ids][]", p.id, @characteristic.properties.include?(p)  %>

我改为

<%= hidden_field_tag "characteristic[property_ids][]", '' %>
...
<%= check_box_tag "characteristic[property_ids][]", p.id, @characteristic.properties.include?(p)  %>

并在控制器中

def characteristic_params
          params[:characteristic][:property_ids] ||= []
          params.require(:characteristic).permit(:characteristicable_id, :characteristicable_type, :property_ids)

        end

def characteristic_params
  params.require(:characteristic).permit(:characteristicable_id, :characteristicable_type, { :property_ids => [] })
end

我关注screencast但是Rails 4希望HABTM为 {:child_id =&gt; []} 和表单应该有 parentmodel [child_ids] [] 但不能 parentmodel [:child_ids] [] ,否则会导致“未经许可的参数:: child_ids “

1 个答案:

答案 0 :(得分:0)

如果params[:characteristic]不存在,则会返回nil。如果它返回nil,那么你正在调用nil[:property_ids],这会抛出一个错误,因为nil不支持括号表示法。

直接解决这个问题的方法是使用三元运算符:

ids = params[:characteristic] ? params[:characteristic][:property_ids] : []

然后你可以mergeids改为params,如果你想做的话。您可能必须调整数据类型以匹配(数组与散列),具体取决于它们的进入方式,但这会让您超过undefined method错误。