开发者

Rails 3 object.belongs_to_id to object.belongs_to.name?

开发者 https://www.devze.com 2023-01-28 17:58 出处:网络
I have a rails 3 project where the index.html.erb currently includes <td><%= chapter.university_id %></td> whereas what I want it to show should be <开发者_StackOverflow;td><

I have a rails 3 project where the index.html.erb currently includes <td><%= chapter.university_id %></td> whereas what I want it to show should be <开发者_StackOverflow;td><%= chapter.university.name %></td> however, this is currently throwing the exception undefined method `name' for nil:NilClass Interestingly, chapter.foo.name is working to access information from another model to which "chapter" belongs. Can anyone help standardize this?

EDIT:

In an attempt to replicate this error in another way, I changed <td><%= chapter.university.name %></td> to <td><%= chapter.university.id %></td>, hoping that I could convince rails to give me university_id from the universities table, rather than the chapters table. Still no luck, but gave the error Called id for nil, which would mistakenly be 4 -- if you really wanted the id of nil, use object_id rather than undefined method `name' for nil:NilClass which I had previously been receiving.

I have also checked and re-checked the 'has_many'/'belongs_to' relationships between chapter and university as well as chapter and foo and found the working and non-working relationships to be identical. I have even gone so far as to switch the order in which those relationships are declared within the models, to no effect.


This turns out to have been a problem with the way fixtures were loading into the database. Dependencies were not being observed, and so random data was being placed into the university_id column on the universities table. Cleaning out the bad data and replacing it with manually entered data solved the problem.

0

精彩评论

暂无评论...
验证码 换一张
取 消