【发布时间】:2023-03-17 08:26:01
【问题描述】:
所以我有一个用户表单form_for,它接受来自 account_prices 的嵌套属性。发生的事情发生在我的用户控制器上,我有这个私有方法。
def pre_build_user_account_prices
if @user.account_prices.empty?
@accountable_default = @user.account_prices.build(status: 'default')
@accountable_temporary = @user.account_prices.build(status: 'temporary')
else
@accountable_default = @user.account_prices.where(status: 'default')
@accountable_temporary = @user.account_prices.where(status: 'temporary')
end
end
条件的原因是,如果我不在这里进行检查,它将呈现 2 个表单。一个空的表格和带有数据的表格。所以这里需要检查
但我的问题是这个。我在编辑路线上,当我尝试提交无效表单时,它会呈现多个空表单。这是一个图像。
如果我一直提交无效表单,它将呈现多次。我在想如果通过 JS 检查是否有多个孩子,我会删除它。这是最好的方法吗?
这是我的关联
Class User
has_many :account_prices, as: :accountable, autosave: true
accepts_nested_attributes_for :account_prices
end
多态
class AccountPrice
enum status: {default: 'default', temporary: 'temporary'}
validates :accountable, presence: true
validates :status, presence: true
validates :exp_start_date, presence: true, if: :is_temporary_status?
validates :exp_end_date, presence: true, if: :is_temporary_status?
belongs_to :accountable, polymorphic: true
belongs_to :variant_price_set, class_name: "Spree::VariantPriceSet"
belongs_to :shipping_method_price_set, class_name: "Spree::ShippingMethodPriceSet"
def is_temporary_status?
status == 'temporary'
end
end
用户控制器
Class UsersController
before_action :pre_build_user_account_prices, only: :edit
def update
if @user.update_attributes(user_params)
flash.now[:success] = Spree.t(:account_updated)
redirect_to show_admin_user_path(@user)
else
render :edit
end
end
def pre_build_user_account_prices
if @user.account_prices.empty?
@accountable_default = @user.account_prices.build(status: 'default')
@accountable_temporary = @user.account_prices.build(status: 'temporary')
else
@accountable_default = @user.account_prices.where(status: 'default')
@accountable_temporary = @user.account_prices.where(status: 'temporary')
end
end
end
【问题讨论】:
标签: ruby-on-rails nested-form-for