Forum: Ruby on Rails "for column in..." not picking up _id columns

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Ryan (Guest)
on 2006-04-27 23:37
My code executes fully:

  <% for column in ModelName.content_columns %>
    <th><%= column.human_name %></th>
  <% end %>

but it does not pick up any columns in my model's table that end in
"_id".

Is this by design?

Is there a helper method that will reference the related tables?  Or
will I need to code the column titles and detail records by hand?

Learning...
Ray Baxter (Guest)
on 2006-04-27 23:54
(Received via mailing list)
Ryan wrote:
>
Yes. From
http://api.rubyonrails.com/classes/ActiveRecord/Ba...

"Returns an array of column objects where the primary id, all columns
ending in "_id" or "_count", and columns used for single table
inheritance have been removed."

> Is there a helper method that will reference the related tables?  Or
> will I need to code the column titles and detail records by hand?

You want to use ModelName.columns if you want the columns ending in _id.

> Learning...

http://api.rubyonrails.com/ is your friend and teacher. You can look at
the source for content_columns if you want to reject some of the other
columns that content_columns rejects, but keep the columns ending in
_id.


--

Ray
Alan Francis (Guest)
on 2006-04-27 23:56
Ryan wrote:
>
> My code executes fully:
>
>   <% for column in ModelName.content_columns %>
>     <th><%= column.human_name %></th>
>   <% end %>
>
> but it does not pick up any columns in my model's table that end in
> "_id".
>
> Is this by design?
>
> Is there a helper method that will reference the related tables?  Or
> will I need to code the column titles and detail records by hand?
>
> Learning...

The ..._id columns are not "content_columns" according to rails.
They're used to link to other models.

If you have Company containing many People, the people table will have a
company_id that links back to the company.

In Rails, you'd have the following models:

class Person < ActiveRecord::Base
  belongs_to :company
end

class Company < ActiveRecord::Base
  has_many :people
end

With that in place, and the correctly named _id field in the people
table, you can do the following:

person = Person.find(:first)
person.company (this is a Company object)

or

company = Company.find(:first)
company.people (this is an array of Person objects)

You could add person to the company like this:

company.people << person

I recommend you stop typing at this point and read the Agile Web Dev
book before going any further.  I promise it'll be worth it.

Alan
This topic is locked and can not be replied to.