一个模型有多个belongs_to
我有这个模型“评论”,它是由给定“城市”和“部门”的模型“用户”给出的。 在为表“comments”创建架构时,我放入了 city_id、department_id 和 user_id 列,它们应充当表城市、部门和用户中各自 id 的外键。
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :city
belongs_to :department
end
城市和部门是独立的表,其中填充了参考数据(将用于填充表单)。
当我尝试访问 comment.city.name 时,我得到一个“nil:NilClass 的未定义方法‘name’”。 表城市由列“id”、“name”和“symbol”定义。 这个错误的根本原因是什么? 我还需要做什么?我什至尝试过将 has_many :feedbacks 放在类 City 和类 Department 中(尽管它不应该发生,因为它们独立于评论)。看来我在这里缺少一些基本的东西。
谢谢, 阿什什
I have this model "Comment" which is given by a model "User" for a given "city" and "department".
While creating the schema for table "comments", I put in columns city_id, department_id and user_id which should act as foreign keys to respective ids in tables cities, departments and users.
class Comment < ActiveRecord::Base
belongs_to :user
belongs_to :city
belongs_to :department
end
Cities and Departments are independent tables which are populated with reference data (which would be used to populate in the forms.
When I try to access comment.city.name, I get a "undefined method `name' for nil:NilClass".
Table cities is defined with columns -"id", "name" and "symbol".
What is the root cause of this error?
What else do I need to do ? I have tried even by putting has_many :feedbacks in class City and class Department (even though it should not happen because they are independent of comments). I am missing something basic here, it seems.
Thanks,
Ashish
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为你需要一个 has_many 来匹配每个 owns_to 。所以你的每个评论所属的类(用户,城市,部门)应该有
I think you need a has_many to go with every belongs_to. So each of your classes that comments belong_to (User, City, Department) should have