我有一个与学校有关联的用户模型(用户包含一个名为school_id的外键)。当用户注册(或创建)时,用户可以选择指定他们参加的学校。我目前遇到的问题是,一旦用户通过学校名称,我不确定如何设置school_id。我目前收到的错误是"未定义的方法`id'为零:NilClass"为:
class User < ActiveRecord::Base
extend FriendlyId
belongs_to :school
#... other code
before_validation :find_school_id
def find_school_id
self.school_id = School.find_by(name: self.school).id
end
end
查看
<div>
<%= f.label :school %>
<%= f.autocomplete_field :school, autocomplete_school_name_suggestions_path %>
</div>
答案 0 :(得分:0)
尝试:
型号:
class User < ActiveRecord::Base
extend FriendlyId
belongs_to :school
#... other code
before_validation :find_school_id
def school_name=(value)
self.school = School.find_by(name: value)
end
def school_name
school && school.name
end
end
查看:
<div>
<%= f.label :school_name %>
<%= f.autocomplete_field :school_name, autocomplete_school_name_suggestions_path %>
</div>