【发布时间】:2020-11-28 00:56:41
【问题描述】:
我仍然是 Rails 的初学者。我想根据关联选择使用数据库中已有的另一个模型的数据填充模型中的某些表单字段。以下是我的代码。
股票购买模式
class StockPurchase < ApplicationRecord
belongs_to :stock
end
库存模型
class Stock < ApplicationRecord
has_many :stock_purchases
end
股票购买表格
<%= simple_form_for(@stock_purchase) do |f| %>
<%= f.error_notification %>
<%= f.error_notification message: f.object.errors[:base].to_sentence if f.object.errors[:base].present? %>
<%= f.association :stock, prompt: "Select Product", input_html: { class: "form-control" } %>
<%= f.input :expiry_date, input_html: { class: "form-control" } %>
<%= f.input :selling_price, as: :currency, input_html: { class: "form-control", placeholder: "Selling Price" } %>
<%= f.button :submit %>
<% end %>
我的控制器
def new
@stock_purchase = current_user.stock_purchases.build
@stocks = Stock.all
end
在表格中,我想根据所选股票从数据库中填写到期日期和售价。
请问我该怎么做。
【问题讨论】:
-
你的控制器里有代码吗?
-
您的控制器中只有“新”,还是也有“编辑”?您在上面发布的“表单”是否同时用于“新建”和“编辑”?
-
因为它是新方法,您刚刚创建的“@stock_purchase”有 nil 字段,您必须先填写它们才能进入您的表单。在控制器中尝试“@stock_purchase.expiry_date = DateTime.now”
-
感谢蛇您的评论,但我想要实现的是,当从股票选择字段中选择股票时,应从所选股票数据库表中获取到期日和售价股票编号并填写到期日和售价
-
你可以使用 JS 来实现。创建一个在选择更改时触发的事件侦听器。让它向服务器发出 AJAX 请求,然后发回你需要的数据。
标签: ruby-on-rails ruby