Rails:来自一个 table/model 的两个引用

Rails: two references from one table/model

我生成了:

rails g model EventTime name:string start_time:datetime post:references city_id:integer

和模特:

class Post < ActiveRecord::Base
  belongs_to :user
  has_many :event_times

class EventTime < ActiveRecord::Base
  belongs_to :post
  belongs_to :city, class_name: 'Post', foreign_key: "city_id"

Post table 中,我们有一行 city_id 具有值。

但是当我尝试像这里这样创建一个新的 event_time 时:

@post = Post.find(1)
  @event = @post.event_times.build(name: '123')
  @event.save

保存后我只得到post_id保存的权限,city_id为NULL

我找不到我的错误。

也欢迎改进代码的提示:)

在您的 Post 模型中,与事件时间的 has_many 关系引用以 post_id 作为外键的事件。我不知道你为什么要在两列中存储相同的 post_id。但要这样做,您应该按如下方式编辑代码。

class Post < ActiveRecord::Base
  belongs_to :user
  has_many :event_times
  has_many :event_locations, foreign_key: "city_id", class_name: "EventTime"
end

尽管如果您使用 @post.event_times.build(name: '123') 构建 EventTime class 的实例,它将在 post_id 和 [=18= 中分配 post id ] 将是 nil,如果您使用 @post.event_locations.build(name: '123') 构建它,将分配 city_id,而 post_id 将是 nil。所以最好的方法是自己分配其中一列,例如 @post.event_times.build(name: '123', city_id: @post.id)