如何在具有多个键和值的hstore数据类型中存储数据rails

时间:2016-07-12 07:44:07

标签: postgresql ruby-on-rails-5 hstore

视图/ _form.html.erb

Extra fee field name : <%= text_field_tag :extra_fee_field,nil, placeholder: 'Enter field name',name: "payment_plan[payment_fees[extra_fee_field]][]" %>fees 
Extra fee value : <%= text_field_tag :extra_fee_value,nil, placeholder: 'Enter fee value in %',name: "payment_plan[payment_fees[extra_fee_value]][]" %> %
<%= submit_tag "Add",id: "add" %>

控制器/ payment_plan_controller.rb

def create
@payment_plan = PaymentPlan.new(payment_plan_params)
@payment_plan.save

private
def payment_plan_params
    params.require(:payment_plan).permit(:pay_within_days,:display_active,
    :payment_fees=>[:extra_fee_field=>[],:extra_fee_value=>[]])
end

模型/ payment_plan.rb

class PaymentPlan < ApplicationRecord
store_accessor :payment_fees
end

以下格式存储数据: -

payment_fees:{“extra_fee_field”=&gt;“[\”serfere \“,\”sfsdfdff \“]”,“extra_fee_value”=&gt;“[\”5 \“,\”7 \“]”} ,display_active:false,created_at:“2016-07-12 06:41:48”,updated_at:“2016-07-12 06:41:48”&gt;

请帮帮我。 在此先感谢.. :))

1 个答案:

答案 0 :(得分:0)

在尝试了我的最佳之后,我得到的解决方案以上所有代码都是正确的,只需改变控制器的方法

@extra_fee_field = params[:payment_plan][:payment_fees][:extra_fee_field]
@extra_fee_value = params[:payment_plan][:payment_fees][:extra_fee_value]
@payment_plan[:payment_fees] = @extra_fee_field.zip(@extra_fee_value).to_h

在此之后,我可以将数据存储在hstore数据类型