I have a Report model that belongs_to a Location model. When accessing a report object within a nested partial, I get a nil value for report.location when I get the desired value in the parent partial as well as in the initial view that includes the partials.
For example,
in the view for the reports/index action, I have can refer to the related locations for individual elements in a @reports array and get the desired value:
@reports[0].location.name # Works
From this view, I render a partial:
render :partial => "reports/reports_table", :locals => { :reports => @reports }
Within the reports_table partial, I can still refer to the location of an individual element of the array of reports and get a could value:
reports[0].location.name # Works
From this view, I render a partial for each individual element of the local reports array:
reports.each do |report|
render :partial => "reports/report_display_row", :locals => { :report => report }
end
but within this second-level partial (report_display_row) I get a nil value for the associated location for each individual report:
report.location.name # undefined method `name' for nil:NilClass
I have tried variations and regardless of what I've tried, it seems in this nested partial objects associated with 开发者_运维技巧my instance of Report are always nil.
You are counting on that report always has a location. Now at least one of them doesn't. Use report.location.try(:name)
to get around the error.
If you want to make location mandatory add this validation to your report model:
validates :location, :presence => true
精彩评论