就算是1:1的关系,`has_one` 和 `belongs_to` 也不能随处乱放,必须是存`外键`的那个表的 Model 用`belongs_to`,另一个表的 Model 用`has_one`。
案例:
clazzs表
create_table "clazzs" do |t|
t.string "name"
t.integer "teacher_id"
end
models#user.rb
class User < ApplicationRecord
has_one :clazz, class_name:"Clazz", foreign_key:"teacher_id"
end
models#clazz.rbclass Clazz < ApplicationRecord
belongs_to :user, class_name:"User", foreign_key:"teacher_id", optional: true
end
注意事项:
- `belongs_to`这一端,如果不是必填内容,最好加上`optional: true`,否则在创建的时候会 => ROLLBACK(Rails_5_之后的特点)
- `has_many :clazz`其中的`clazz`可以随意命名,方便理解、查询为原则,可以不是对应的Model的名字,不过在找它的时候,`:`后面是什么,就必须用什么来找。如果改成`cla`,那么就用`User.first.cla`