Cocoon显示对象而不是值

时间:2015-04-08 01:01:19

标签: ruby-on-rails ruby nested simple-form cocoon-gem

我的情况:

"应用程序/模型/ aircraft.rb"

class Aircraft < ActiveRecord::Base
  has_many :aircraft_crew_roles
  has_many :crew_roles, through: :aircraft_crew_roles, class_name: 'CrewRole'
end

&#34;应用程序/模型/ aircraft_crew_role.rb&#34;

aircraft_id
crew_role_id

class AircraftCrewRole < ActiveRecord::Base
  belongs_to :aircraft
  belongs_to :crew_role
  accepts_nested_attributes_for :crew_role, reject_if: :all_blank
end

&#34;应用程序/模型/ crew_role.rb&#34;

name

class CrewRole < ActiveRecord::Base
end

&#34;应用程序/视图/飞机/ _form.html.haml&#34;

= simple_form_for(@aircraft) do |f|
  = f.error_notification
  = f.input :name
  #crew
    = f.simple_fields_for :aircraft_crew_roles do |cr|
      = render 'aircrafts/aircraft_crew_role', :f => cr
    = link_to_add_association 'add a Crew Role', f, :aircraft_crew_roles, partial: "aircrafts/aircraft_crew_role"

  = f.button :submit

&#34;应用程序/视图/飞机/ _aircraft_crew_role.html.haml&#34;

.nested-fields.crew-fields
  #crew_from_list
    = f.association :crew_role, as: :select, collection: CrewRole.all()
  = link_to_add_association 'or create a new Role', f, :crew_role
  = link_to_remove_association "remove Role", f

&#34;应用程序/视图/飞机/ _crew_role_fields.html.haml&#34;

.nested-fields
  = f.input :role

这是我目前的情况,几乎一切正常:我可以在飞机上添加新的机组成员,这将在aircraft_crew_role和crew_role表中创建相应的条目,如果我连接到数据库,我可以看到所有条目是对的(我看到所有ID和crew_role表中的角色都是我在表单中使用的那个)但如果我尝试使用已经保存在前一架飞机上的工作人员,则选择用对象而不是字符串填充:

#<CrewRole:0x007fa90d2f8df8>
#<CrewRole:0x007fa90d2f8c90>
#<CrewRole:0x007fa90d2f8b28>

我已经在应用程序的许多其他地方使用过cocoon,并且在其他所有地方都运行得很顺利。 我已将我的代码与cocoon repo上的示例进行了比较,但我无法找到问题

2 个答案:

答案 0 :(得分:1)

您正在使用simple_form&#39; f.association,它会尝试猜测如何呈现CrewRole对象。它会查找namelabel或普通的to_s ...在您的情况下,它是非标准字段role,因此它只会将模型转换为字符串(给出你得到的结果)。

要解决这个问题,你必须重命名你的专栏(有点激烈,但也许这就是你在重新创建数据库时所做的那样?)或者更好,写一些类似

的内容
= f.association :crew_role, label_method: :role

有关详情,请参阅simple_form documentation

答案 1 :(得分:0)

我绝对不知道如何“简单地”删除并重新创建数据库,现在一切顺利。