【发布时间】:2013-12-02 00:51:18
【问题描述】:
我正在构建一个应用程序,用户可以在其中创建公司并添加对该公司的投资。投资可以来自两个来源用户的基金或公司的共同投资者。资金在应用程序中很重要,因为用户可以在其中做很多事情。共同投资者并不那么重要,但我想控制其中的几个方面,所以我为他们创建了一个模型。为此,我创建了一个多态关联,为此我给出了 [可怕的] Investables 名称。我正在运行 Rails 3.2.15 和 Ruby 2.0.0。型号如下:
class Company < ActiveRecord::Base
has_many :investments
accepts_nested_attributes_for :investments
end
class Investment < ActiveRecord::Base
belongs_to :fund, :class_name => "Fund", :foreign_key => 'investable_id'
belongs_to :company, inverse_of: :investments
belongs_to :coinvestor, :class_name => "Coinvestor", :foreign_key => 'investable_id'
end
class Fund < ActiveRecord::Base
has_many :investments, :as => :investable, :dependent => :destroy
end
class Coinvestor < ActiveRecord::Base
has_many :investments, :as => :investable, :dependent => :destroy
end
在编辑公司时,我希望能够添加投资,并且我希望为每项新投资动态添加表格行。在很棒的165-Edit Multiple Revised 之后,我能够做到这一点。
为了使其更复杂,我还想添加一个下拉列表来选择多态类型,以便过滤下一个下拉列表以仅显示基金或共同投资者的名称。 为此,我主要改编了来自Railscast 88-Dynamic Select Menus的代码(谢谢瑞恩!!)
/views/company/edit.html.erb
<%= form_for(@company) do |f| %>
...
<%= f.fields_for :investments do |builder| %>
<%= render 'investment_fields', f: builder %>
<% end %>
<%= link_to_add_fields "Add Investment", f, :investments, 'table' %>
/views/company/_investment_fields.html.erb
<%= f.select :investable_type , [ "Fund", "Coinvestor" ], {prompt: "Investor Type"} %>
<%= f.grouped_collection_select( :investable_id, investables_to_collection, :investables, :name, :id, :name, {prompt: "Investor"} ) %>
“investable_to_collection”是我构建的一个助手,用于聚合来自 Funds 和 Coinvestors 模型的对象。
module CompaniesHelper
InvestableCollection = Struct.new(:name, :investables)
CollectionItem = Struct.new(:name, :id)
def investables_to_collection
a = Array.new
a << InvestableCollection.new('Fund', Fund.all.map { |item| CollectionItem.new(item.name, item.id )})
a << InvestableCollection.new('Coinvestor', Coinvestor.all.map { |item| CollectionItem.new(item.name, item.id )})
a
end
end
我还没有添加任何 JavaScript 来过滤下拉列表,这将是另一个挑战。但是我有我的美丽视图来显示我已经在数据库中获得的数据。但是应该显示基金或共同投资者名称的下拉菜单会混淆:即使投资是由基金进行的,它也会显示 ID == 1 的共同投资者的名称。
我想让其中一个模型具有自定义 ID,例如 f1、f2、f3 ... 而不是 1、2、3...,这样系统就不会混合它们。但它似乎会产生其他大的兼容性问题。
大家还有什么想法吗?
【问题讨论】:
标签: drop-down-menu ruby-on-rails-3.2 polymorphic-associations