【问题标题】:How to handle data from nested forms in Rails 4 with cocoon gem?如何使用茧宝石处理Rails 4中嵌套表单的数据?
【发布时间】:2015-04-17 08:53:17
【问题描述】:

我正在使用 Cocoon gem 来做嵌套表单。 我有这样的模型:

# request.rb
has_many :filled_cartridges, inverse_of: :request, dependent: :destroy
	accepts_nested_attributes_for :filled_cartridges, :reject_if => :all_blank, allow_destroy: true

#filled_cartridge.rb
belongs_to :request

在我的 form_for @request 内部,我有这样的嵌套表单:

<div id="filled_cartridges">
  <%= f.fields_for :filled_cartridges do |filled_cartridge| %>
    <%= render 'filled_cartridge_fields', f: filled_cartridge %> 	
  <% end %>
<div class="links">
  <%= link_to_add_association 'add', f, :filled_cartridges %>
</div>

fill_cartridge_fields partial 是这样的:

<fieldset>
  <%= f.text_field :cartridge_id %>
  <%= f.hidden_field :_destroy %>
  <%= link_to_remove_association "remove", f %>
</fieldset>

当我点击“添加”时,它又添加了一个。单击“删除”时,它会删除 . 当我提交表单时,嵌套表单的参数如下所示:

filled_cartridges_attributes: !ruby/hash:ActionController::Parameters
    '0': !ruby/hash:ActionController::Parameters
      cartridge_id: '12'
      _destroy: 'false'
    '1429260587813': !ruby/hash:ActionController::Parameters
      cartridge_id: '2'
      _destroy: 'false'
我如何访问这些参数,以及如何保存它们。如何遍历这些参数并保存它们,或者 Cocoon gem 是否有一些内置功能?最后如何检查这些参数是否设置?因为它是嵌套的,所以它欺骗了我。 编辑:我的 request_controllers#create:

def create 
  @request = Request.new( request_params )
  # code for handling Request model	 
  # here i want to handle nested model too (filled_cartridge)
  @request.save
  if @request.save
     flash[:success] = "Заявка была добавлена"
     redirect_to @request
  else 
     render 'new'	
  end
end

EDIT2:我的强参数:

def request_params
  params.require(:request).permit(:name, :address, :phone, :mobile, :type, :description, :priority, :responsible, :price, :payed, :date, filled_cartridges_attributes: [:cartridge_id, :_destroy], :stype_ids => [], :social_media =>[])
end

【问题讨论】:

  • 你能粘贴你的控制器代码吗?
  • @japed 我已经编辑了我的帖子
  • request_params 方法中有什么?我猜你没有告诉 strong_parameters 接受filled_cartridges_attributes
  • @japed 我编辑了我的帖子。
  • @japed,我明白了。我传递了错误的参数,而不是我需要传递的 id 墨盒 ID。但我不希望自动保存记录,我需要在保存之前访问这些参数并做一些事情。

标签: ruby-on-rails ruby cocoon-gem


【解决方案1】:

在最近一个使用 cocoon 的项目中,我必须访问要保存的属性的参数。我在我的控制器中的创建操作中找到了一个代码。诀窍是了解如何检索将要保存的属性的哈希键。哈希的关键是参数中的数字“1429260587813”

 ...
'1429260587813': !ruby/hash:ActionController::Parameters
  cartridge_id: '2'
  _destroy: 'false'

因此,您需要在创建操作中创建一个循环,以使用 ruby​​ 哈希方法“keys”检索此密钥。我做了一个循环,因为在使用 cocoon 动态嵌套字段时,我可能一次创建多个嵌套属性,因此这意味着要检索多个键。

这是对我有用的代码,请阅读我的 cmets,其中解释了此代码的不同步骤。我希望它能帮助你适应你的需要。

    #Here I just initialize an empty array for later use
    info_arr = []
    #First I check that the targeted params exist (I had this need for my app) 
    if not params[:recipe]["informations_attributes"].nil?
        #z variable will tell me how many attributes are to be saved
        z = params[:recipe]["informations_attributes"].keys.count
        x = 0
        #Initiate loop to go through each of the attribute to be saved
        while x < z
            #Get the key (remember the number from above) of the first hash (params) attribute
            key = params[:recipe]["informations_attributes"].keys[x]
            #use that key to get the content of the attribtue
            value = params[:recipe]["informations_attributes"][key]
            #push the content to an array (I had to do this for my project)
            info_arr.push(value)
            #Through the loop you can perform actions to each single attribute
            #In my case, for each attributes I creates a new information association with recipe
            @recipe.informations.new(title: info_arr[x]["title"]).save
            x = x +1
        end
    end

这项工作用于访问茧嵌套属性内容并根据您的需要应用操作。这对我有用,因此您应该能够使用此示例代码并根据您的需要对其进行调整。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-01-18
    • 2023-03-20
    • 1970-01-01
    • 1970-01-01
    • 2019-09-24
    相关资源
    最近更新 更多