You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails表单需求:固定产品名称输入框并设置售价成本默认值

问题解决:产品添加到门店表单的预设值与固定字段实现

需求说明

开发outletproduct页面的表单,从产品详情页点击「添加产品到门店」跳转后,需实现:

  • 表单显示所选产品名称,且不可修改;
  • selling_price和last_cost输入框默认显示产品原有价格与成本,支持修改。

原代码问题分析

  1. Controller层:new方法中@product = Product.all获取所有产品,未定位到用户选中的单个产品;未预设表单字段的默认值。
  2. 视图层:f.text_field :@product.name语法错误;selling_price和last_cost的默认值设置方式不正确;未传递product_id用于表单提交关联。

修改后的代码实现

OutletProduct Controller

class OutletProductsController < ApplicationController
  def new
    # 通过跳转时携带的product_id参数获取目标产品
    @product = Product.find(params[:product_id])
    # 初始化OutletProduct时预设价格和成本
    @outlet_product = OutletProduct.new(
      selling_price: @product.price,
      last_cost: @product.cost
    )
    @outlets = Outlet.all
  end

  def index
  end

  def show
  end

  def create
    @outlet_product = OutletProduct.new(outlet_product_params)
    if @outlet_product.save
      flash[:success] = "创建成功!"
      redirect_to @outlet_product
    else
      # 保存失败时重新获取产品实例,避免页面报错
      @product = Product.find(@outlet_product.product_id)
      @outlets = Outlet.all
      render 'new'
    end
  end

  def edit
  end

  private
  def outlet_product_params
    params.require(:outlet_product).permit(:product_id, :outlet_id, :quantity,
                                          :selling_price ,:last_cost)
  end
end

new.html.erb视图

<h1>添加产品到门店</h1>
<div class="row">
  <div class="col-md-6 col-md-offset-3">
    <%= form_with(model: @outlet_product, local: true) do |f| %>
      <%= render 'shared/error_messages', object: f.object %>

      <%= f.label :product_name %>
      <!-- 禁用输入框显示产品名,隐藏字段传递product_id用于提交 -->
      <%= f.text_field :product_name, value: @product.name, disabled: true, class: "form-control" %>
      <%= f.hidden_field :product_id, value: @product.id %>

      <%= f.label :quantity %>
      <%= f.number_field :quantity, class: "form-control" %>

      <%= f.label :selling_price %>
      <%= f.number_field :selling_price, class: 'form-control' %>

      <%= f.label :last_cost %>
      <%= f.number_field :last_cost, class: 'form-control' %>

      <%= f.label :outlet_id %>
      <%= f.select(:outlet_id, @outlets.collect { |outlet| [ outlet.name, outlet.id] }, {}, class: "form-select") %>

      <%= f.submit "提交", class: "btn btn-primary" %>
    <% end %>
  </div>
</div>

关键修改点说明

  • 跳转时需确保「添加产品到门店」按钮的链接携带product_id参数(例如:<%= link_to '添加产品到门店', new_outlet_product_path(product_id: @product.id) %>);
  • 产品名称通过禁用的输入框展示,同时用隐藏字段传递product_id,既保证不可修改又能正确关联产品;
  • 在Controller初始化OutletProduct时预设价格和成本,表单会自动填充默认值,无需在视图层重复设置;
  • 保存失败时重新获取产品实例,避免页面渲染时出现变量缺失错误。

内容的提问来源于stack exchange,提问作者cherry123

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.18 07:20:29