ruby on rails - iterating data from 2 models -
in index i'm trying iterate through records through records in 2 models, job , employer. i've set has_many relationship.
rails throwing undefined method `each' #
job model
attr_accessible :title, :location belongs_to :employer
employer model
attr_accessible :companyname has_many :jobs
job controller
def index @jobs = job.find(:all, :include => :employer)
index
<% @jobs.each |job| %> <%= job.title %> <%= job.location %> <% job.employer.each |employer| %> <% employer.companyname %> <% end %> <% end %>
that's because job has 1 employer, not many. that's belongs_to means. see rails guide setting actual many-to-many relationships.
but think in case do want one-to-many. why job have multiple employers? instead, output single employer company name.
more info
you still want belongs_to on job model. belongs_to go on models have foreign key referencing other model. in case, job model has id pointing @ employer (it has employer_id field). has_one or has_many associations when no foreign key exists on model relationship still exists.
so job model has method called employer
(singular) not employers
(plural) because belongs to single employer. employer has many
jobs under them, has_many association gives jobs
(plural) method, not job
(singular) method.
the link posted rails guide excellent job of showing more of this, more details , explanation, , more examples.
addtional code bit
with above, want change code this:
<% @jobs.each |job| %> <%= job.title %> <%= job.location %> <%= job.employer.companyname %> <% end %>
notice how can go straight accessing attributes on employer want. , it!
Comments
Post a Comment