选项选择与参考



>我有 2 种型号:Unit 和 Emp 我还有 2 个控制器:单位和 EMPS

class CreateEmps < ActiveRecord::Migration[6.0]
def change
create_table :emps do |t|
t.string :name
t.references :unit
t.timestamps
end
end
end
class CreateUnits < ActiveRecord::Migration[6.0]
def change
create_table :units do |t|
t.string :name
t.timestamps
end
end
end

看起来很简单。但我想太简单了。我还没有找到如何执行以下操作的示例:

我需要有用于创建 Emp 的表单。

所以我的问题是....它应该是什么样子的?

我想让组合框包含单位中所有对象的列表。

<%= form_with model: @emp do |f| %>
<p><%= f.label :name %>
<%= f.text_field :name %> </p>
<!-- What should go here? to ComboBox (option->select) -->
<%= f.submit "Create" %>
<% end %>

我也感到困惑,它应该看起来像

是重新emp_params许可。编辑:

class EmpsController < ApplicationController
def new
@emp = Emp.new
@unit_options = Unit.all.collect{|unit| [unit.name, unit.id] }
end
def create
@emp = Emp.new(emp_params)
@emp.save
redirect_to :action => :list
end
def destroy
@emp = Emp.find([:id])
@emp.destroy
redirect_to :action => :list
end
def list
@emps = Emp.all
end
def emp_params
params.require(:emp).permit(:name, :unit_id)
end
end

您想要使用选择标签。

在控制器中:

@unit_options = Unit.all.collect{|unit| [unit.name, unit.id] }

这将创建一个名称和 ID 列表,每个名称和 ID 的顺序是名称,然后选择选项的值。当然,您可以根据需要确定结果的范围或过滤结果。

在您看来:

<%= form_with model: @emp do |f| %>
<div>
<%= f.label :name %>
<%= f.text_field :name %>
</div>
<div>
<%= f.label :unit_id, 'Unit' %>
<%= f.select :unit_id, @unit_options, {include_blank: true} %>
</div>
<%= f.submit "Create" %>
<% end %>

用于编辑模型时,轨道将为当前值选择选项。

最新更新