从Rails的两个表中合并下拉菜单

时间:2019-07-12 02:04:44

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

我想知道如何合并两个表属性并在一个下拉列表中对其进行汇总。

我试图在创建表单助手中创建一个方法,该方法引用了表的属性。


_form.html.erb

<div class="field">
    <%= form.label :Destinations %>
    <%= form.collection_select(:destination_id, Destination.all, :id, destname_with_klm(@createform.destination), {}, { :multiple => false } ) %>
  </div>

createforms_helper.rb

module CreateformsHelper

  def destname_with_klm(f)
    "#{f.Destination_name}.#{f.Destination_kilometre}"
end
end
NoMethodError in Createforms#new
Showing **/app/views/createforms/_form.html.erb where line #34 raised:

undefined method `Destination_name' for nil:NilClass

1 个答案:

答案 0 :(得分:0)

您收到undefined method "Destination_name" for nil:NilClass的错误是因为您传递的参数(f)为nil

但是,我认为您可以更新模型并使代码更简洁。 (我查看了格式建议的修改并收集了此信息)

#app/models/destination.rb

class Destination < ActiveRecord::Base
   #other code 
   def destination_name_with_kms
     # I believe the attribute names should be lowercase 
     "#{Destination_name}.#{Destination_kilometre}"
   end
end

#in your view
<%= form.collection_select(:destination_id, Destination.all, :id, destination_name_with_kms, {}, { :multiple => false } ) %>

如果您想更进一步,我建议使用装饰宝石,例如 Draper,然后将所有UI格式移至装饰器。