Activerecord using a Link table with additional information
I have a table structure that uses a link table to relate Jobs to People, the link table contains data information for how long a person was at a particular job.
I have a simple rails application that is trying to get all jobs and display the job's employment date ranges.
class Employment < ActiveRecord::Base
belongs_to :person
belongs_to :job
end
class Job < ActiveRecord::开发者_运维知识库Base
belongs_to :employer
has_many :employment
accepts_nested_attributes_for :employment
end
def index
@jobs = Job.joins(:employment).find(:all)
end
Now when i try to access properties 'employment_started'/ended I get a 'NoMethodError in Experience#index'
undefined method `employment_started' for #<Class:0x000000026927e0>
17: <span><%=job.employment.employment_started%> - <%=job.employment.to_yaml%>
When I use the 'to_yaml' function I can see there is data in the object:
!ruby/object:Employment attributes: job_id: 1 person_id: 1 employment_started: 2008-04-21 employment_ended: attributes_cache: {} changed_attributes: {} destroyed: false marked_for_destruction: false new_record: false previously_changed: {} readonly: false
Why can't rails access this 3'rd level attribute?
When you have a "has_many" relationship , you receive an array. So basically.
Plus, It should be has_one :employment
or has_many :employments
if it is a has_many relationship then you can iteration through the employments array to get the desired result
Like Rishav says, the Job has_many :employments
means that job.employments will be an array. So you can't access the employment_started
attribute directly.
The following code should return one <p>
with the employment_started
value for each of the employments.
<% job.employments.each do |employment| %>
<p><%= employment.employment_started %></p>
<% end %>
精彩评论