jj1111
jj1111

Reputation: 667

rails new column foreign key 'null'

I've successfully created a new column 'page_title' in a table 'schedule_items'. 'page_title' exists in the 'pages' table. 'page_id' exists in the table 'schedule_items' so I know pulling in a foreign key works, and can see in the schedule_item.rb model, the relationship "belongs_to :page". I can't figure out how to make the column 'page_title' pull in the associated 'page_title' column from 'pages' table. Any help is appreciated, thanks!

Upvotes: 0

Views: 309

Answers (1)

Taryn East
Taryn East

Reputation: 27747

Rails has special code that can understand that when you define belongs_to :page that it should look for a column named page_id.

Rails has no code for any other kinds of columns. There is no code that will automatically look for page_title - if you want that, then you need to do something else.

A common way of dealing with this would be to use a delegation eg:

class Schedule
  belongs_to :page
  delegate :title, :to => page

Then you could do something like:

schedule = Schedule.find(12345)
schedule.title # => "Title for page associated with this schedule"

Upvotes: 1

Related Questions