mysql - Rails 嵌套表单属性未显示在表单中

标签 mysql ruby-on-rails forms

我有两个型号:许可证和车辆型号。车辆表有一个permit_id 的外键。我正在尝试将许可证 ID 输入到车辆表中,其中表单上输入的许可证号等于车辆表中的许可证号(不是主键)。

车辆.rb

class Vehicle < ApplicationRecord
self.primary_key = :vehicle_id
belongs_to  :permit, optional: true

permit.rb

class Permit < ApplicationRecord
self.primary_key = :permit_id
has_one :vehicle
accepts_nested_attributes_for :vehicle

permits_controller.rb

class PermitsController < ApplicationController
...
def new
  @permit = Permit.new
  @vehicle = @permit.build_vehicle
end
params.require(:permit).permit(:permit_id.,...,vehicle_attributes: [:license_number])

许可证表格

<%= form_with(model: permit, local: true) do |form| %>
...
<div class="field">
  <% form.fields_for :vehicle do |f| %>
    License:
    <%= f.text_field :license_number, id: :vehicle_license_number %>
  <% end %>
</div>

我的第一个问题是我的嵌套属性 license_number 根本没有显示在我的字段中。我可以在 chrome 元素中看到 div,但文本字段没有显示。我的第二个问题是如何在车辆表中搜索license_number等于输入的许可证号的位置,然后将permit_id放入同一行?

最佳答案

我不知道是什么原因导致您的第一个问题,但您应该保留 id: :vehicle_license_number 部分,并使用 f.label 添加实际标签。

要查找车辆,您可以使用 vehicle = Vehicle.find_by(license_number: allowed_pa​​rams[:vehicle_attributes][:license_number] ,然后使用 @permit.update(vehicle: Vehicle) 保存)。话虽如此,我认为您不需要使用 filed_foraccepts_nested_attributes_for

关于mysql - Rails 嵌套表单属性未显示在表单中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47316281/

相关文章:

MySQL根据第二个表中的匹配信息从表中选择信息

css - 在 rails 中使用背景图片

php - 我可以从另一个网站呈现表单吗

ruby-on-rails - Ruby on Rails : Access values from form in controller

mysql - 补丁后 MAMP 不适用于 Yosemite

mysql 查询 - 为一个巨大的表优化现有的 MAX-MIN 查询

ruby-on-rails - 用户确认帐户后发送欢迎电子邮件

mysql - 如何修复 Zsh 中的 "command not found: mysql"

forms - django-rest-framework - 在可浏览的 API 中自动生成表单?

MySQL:类似数据透视的查询结果