我的应用程序的商家可以接受3种付款方式。为了创建/编辑记录,我在PostgreSQL中使用表单和数组字段中的多个复选框
有趣的是,在创建和更新时,它在保存值时工作正常。根据复选框值,数组作为数组保存在PG表中。但是,在编辑时,编辑表单不会从数据库加载正确的值。所有复选框始终显示为未选中,忽略PG表中的数组值。即使迁移将默认值设置为应该检查的所有复选框,也会在创建时发生相同的事情。
任何帮助都将不胜感激。
创建和编辑的共享视图部分:
= form_for @merchant, layout: :horizontal do |f|
= f.check_box :payment_accepted, { :multiple => true }, 'Credit Card', nil
= f.check_box :payment_accepted, { :multiple => true }, 'Paypal', nil
= f.check_box :payment_accepted, { :multiple => true }, 'Direct Deposit', nil
= f.submit 'Save Changes', :class => 'btn btn-primary'
我的控制器代码是:
class MerchantsController < ApplicationController
load_and_authorize_resource
before_action :set_merchant, only: [:show, :edit, :update, :destroy]
respond_to :html, :json, :js
def index
@merchants = Merchant.all
end
def show
end
def new
@merchant = Merchant.new
end
def edit
end
def create
@merchant = Merchant.new(merchant_params)
@merchant.save
respond_with(@merchant)
end
def update
@merchant.update(merchant_params)
flash[:notice] = 'Merchant was successfully updated.'
respond_with(@merchant)
end
def destroy
@merchant.destroy
redirect_to merchants_url, notice: 'Merchant was successfully destroyed.'
end
private
def set_merchant
@merchant = Merchant.find(params[:id])
end
def merchant_params
params.require(:merchant).permit(:name, :description, :notif_email, :category_id, :country_id, :costo_procesamiento, payment_accepted:[])
end
end
我的迁移:
class CreateMerchants < ActiveRecord::Migration
def change
create_table :merchants do |t|
t.string :name
t.text :description
t.text :default_terms
t.text :notif_email
t.boolean :visible, default: true
t.integer :category_id
t.integer :country_id
t.integer :costo_procesamiento, null:false, default: 0
t.string :payment_accepted, array: true, default: "['Credit Card','Paypal','Direct Deposit']"
t.references :country, index: true, foreign_key: true
t.timestamps null: false
end
end
end
答案 0 :(得分:1)
这是因为虽然复选框知道有多个值,但是它们不知道哪个(它们不能取消选中/未选中的值)。更改您的复选框,以便他们知道何时应该或不应该检查它们:
= f.check_box :payment_accepted, { :multiple => true, checked: @payments.include?('Credit Card')}, 'Credit Card', nil
= f.check_box :payment_accepted, { :multiple => true, checked: @payments.include?('Paypal') }, 'Paypal', nil
= f.check_box :payment_accepted, { :multiple => true, checked: @payments.include?('Direct Deposit') }, 'Direct Deposit', nil
并在您的控制器中添加:
def edit
@payments = @merchant.payment_accepted
end