【问题标题】:Option select with reference选项选择参考
【发布时间】:2019-12-20 19:23:49
【问题描述】:

我有 2 个模型:Unit 和 Emp 我还有 2 个控制器:Units 和 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 的表格。

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

我想要一个包含 Units 中所有对象列表的 ComboBox。

<%= 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

【问题讨论】:

  • 组合框是什么意思?你已经定义了 EMP 属于一个 Unit 那么为什么不直接使用一个选择框呢?
  • 我以前用 C# 编程,所以它被称为组合框
  • 知道了,答案来了

标签: ruby-on-rails ruby forms ruby-on-rails-5


【解决方案1】:

您想使用select tag

在您的控制器中:

@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 %>

用于编辑模型时,rails会选择当前值的选项。

【讨论】:

  • 确实有点成功了。谢谢。尽管现在我遇到了一些不同的问题,但它似乎没有保存在数据库中。虽然没有错误。
  • 你能看一下吗?我提供了完整的控制器定义
  • 没关系...这是错误的关联(必须使用 has_one)非常感谢您的解决方案和圣诞快乐;)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-06-26
  • 2015-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多