新手问题 关于 simple_form association 的问题 (已解决)

levan · 2013年04月09日 · 最后由 Levan 回复于 2013年04月09日 · 3070 次阅读

按照 simple_form 关于 association 的介绍,我的代码是这样的:

class User < ActiveRecord::Base
  #其他代码
  belongs_to :school
end
class School < ActiveRecord::Base
    attr_accessible :name
    has_many :users
    validates_presence_of :name
end

用 devise 建立的用户系统,需要在用户注册的时候选择学校, 在 app/views/devise/registrations/new.html.erb

<div class="controls">
  <%= f.association :school %>
</div>

刷新页面后显示的是:

undefined method `school_id' for #<User:0x007ffc33ada908>

重建了 school model,加入

create_table :schools do |t|
  t.string :name
  t.integer :school_id

  t.timestamps
end

可结果还是一样,请问该怎么解决?才能够让用户注册的时候,选择 school 呢?感谢。

undefined method school_id for #<User:0x007ffc33ada908> 意思是需要在 users table 中有外键 school_id,但是你的 migration 中写的是给 schools table 添加了 school_id 字段,正确的做法是:新建一个 migration,代码如下:

add_column :users, :school_id, :integer
remove_column :schools, :school_id
add_index :users, :school_id

@zzhattzzh 搞定了,谢谢!

需要 登录 后方可回复, 如果你还没有账号请 注册新账号