2015-04-08 72 views
0

我的情况:茧显示对象,而不是看重

“应用程序/模型/ aircraft.rb”

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

“应用程序/模型/ aircraft_crew_role.rb”

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 

“应用程序/ models/crew_role.rb“

name 

class CrewRole < ActiveRecord::Base 
end 

”app/views/aircraftcrafts/form.html.haml”

= 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 

“的应用程序/视图/飞机/ _aircraft_crew_role.html.haml”

.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 

“的应用程序/视图/飞机/ _crew_role_fields.html.haml”

.nested-fields 
    = f.input :role 

这是我目前的情况,几乎所有的工作都很好:我可以为飞机添加新的机组人员,这将在aircraft_crew_role和crew_role表中创建相应的条目,如果我连接到数据库,我可以e所有条目都是正确的(我看到了所有ID,并且crew_role表中的角色是我在表单中使用的角色),但是如果我尝试使用已经与先前飞机保存的机组人员,则选择会填充对象字符串:

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

我已经使用了茧在应用其他许多地方,在所有其他地方它工作顺利。 我比较我的代码与茧回购的例子,但我找不到问题

+0

我对这个环境并不熟悉,但是''to_s'方法向'CrewRole'添加了什么改变? – itdoesntwork

+0

@itdoesntwork没有帮助,因为我认为已经从内部的茧转换。 – Jabawack81

回答

1

您正在使用simple_form的f.association,它将尝试猜测如何呈现CrewRole对象。它寻找name,label或普通老to_s ...在你的情况下,它是一个非标准领域role,所以它只会将模型转换为字符串(给出你得到的结果)。

为了解决这个问题,你将不得不重命名列(有点激烈,但也许这是你做了什么,重新创建数据库时?)或更高,喜欢写东西

= f.association :crew_role, label_method: :role 

见simple_form documentation更多信息。

0

我绝对不知道如何,但“简单”丢弃和重新创建数据库现在一切工作顺利。

相关问题