GEkk
GEkk

Reputation: 1366

Rails: two references from one table/model

I have generated:

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

and the models:

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"

In the Post table we have a row city_id with value.

but when I try to create a new event_time like here:

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

After save I get only the post_id saved right and the city_id is NULL

I can not find my mistake.

Tips to Improve the code are also welcome :)

Upvotes: 1

Views: 100

Answers (1)

Oss
Oss

Reputation: 4322

In your Post model, the has_many relation with event times references events with post_id as the foreign key. I do not know why you want to store the same post_id in two columns. But to do so you should edit your code as follows.

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

Though if you build an instance of the EventTime class using @post.event_times.build(name: '123') it will assign the post id in post_id and city_id will be nil and if you build it using @post.event_locations.build(name: '123'), city_id will be assigned and post_id will be nil. So the best way is to assign one of the columns yourself like @post.event_times.build(name: '123', city_id: @post.id)

Upvotes: 1

Related Questions