2014-09-03 85 views
0

什么是建立一个包含一个选择字段的集合,但值包含在选择需要被从没有一个模型采购最好的,正确的方式simple_forms_for场与调用字段模型的直接关联?Rails的无关联创建集合

比如我有一个simple_forms_for形式类似如下:

<%= simple_form_for(@customer) do |f| %> 
<%= f.error_notification %> 
<fieldset> 
    <div class="form-inputs"> 
    <%= f.input :code, required: true %> 
    <%= f.input :name, required: true %> 
    <%= f.input :location, required: true %> 
    <%= f.input :service_level %> 
    <%= f.input :golive_date, :as => :date_picker %> 
    <%= f.input :connection_type %> 
    <%= f.input :service_centre %> 
    <%= f.input :end_date, :as => :date_picker %> 
    <%= f.input :sla %> 
    <%= f.input :project_code %> 
    </div> 

    <div class="form-actions"> 
    <%= f.button :submit, :class => "btn btn-primary" %> 
    </div> 
</fieldset> 
<% end %> 

我想要做的:service_level字段中的选定字段并添加一个集合到它,但是存储查找值的表没有关联与表格的客户表。

class Lookup < ActiveRecord::Base 
    validates_presence_of :name, :description 
    has_many :lookup_values 
    accepts_nested_attributes_for :lookup_values, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true 
end 

class LookupValue < ActiveRecord::Base 
    belongs_to :lookup 
end 

class CreateLookups < ActiveRecord::Migration 
    def change 
    create_table :lookups do |t| 
     t.string :name 
     t.string :description 

     t.timestamps 
    end 
    end 
end 

class CreateLookupValues < ActiveRecord::Migration 
    def change 
    create_table :lookup_values do |t| 
     t.integer :lookup_id 
     t.string :name 
     t.string :value 

     t.timestamps 
    end 
    end 
end 

我基本上希望能够使用下面的SQL查询来填充选择的值:

select v.name||' - '||v.value 
    from lookup_values v, 
     lookups l 
where v.lookup_id = l.id 
    and l.name = 'Service level'; 

被保存到实际值:service_level字段需要的价值v.name。

所有的收藏品的例子,我只看到了似乎展示了如何创建基于具有它们之间的关联模型选择,只是想知道如果有一个简单的方法来实现这一目标没有关联。

回答

0

好吧,嗯,这是尴尬...

简单的解决办法是修改_form.html.erb视图文件,以便:service_level场原文:

<%= f.input :service_level, :collection => LookupValue.joins(:lookup).where(lookups: { :name => 'Service level' }).pluck(:name) %> 

我可能需要重复的形式多次查找值时,使这更干。

任何想法如何,我可以增强该代码:

  • 删除在选择字段中列出下拉空白值?
  • 修改,在选择下拉显示下拉至 名称值文本||” - '||值。例如示出的值的格式 “L1 - 第1级”。选择并保存需要 的实际值保持为“L1”(即:名称值)
+0

好简单的谷歌搜索回答第一个问题,只是需要加入:include_blank =>假输入字段。 – shwashbuckle 2014-09-06 10:58:41