缺少方法通知belongs_to has_many

时间:2016-06-30 10:04:00

标签: ruby-on-rails

我在使用Rails 4.2.2中的协会工作时遇到了很多麻烦。我有一个项目,这个项目可以有很多通知。我想要的是我可以添加通知:

@project.notifications.build(icon: "icon.jpg", text: "lorem ipsum")

所以我已将belongs_to添加到我创建的Notification模型中,您可以在下面看到:

class Notification < ActiveRecord::Base
 belongs_to :project
 validates :icon, presence: true
 validates :text, presence: true, length: { maximum:75 }
 validates :project_id, presence: true
 enum status: {green: 1, orange: 2, red: 3, dark_grey: 4, light_grey:5}
end

并将has_many关联添加到Project模型中:

class Project < ActiveRecord::Base
 belongs_to :user 
 has_many :notifcations
 before_save :set_start_date
 validates :name, presence: true, length: {maximum: 255}
 validates :website, presence: true
 WEBSITE_REGEX = /\A(?:(?:https?|http):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)(?:\.(?:[a-z\u00a1-\uffff0-9]+-?)*[a-z\u00a1-\uffff0-9]+)*(?:\.(?:[a-z\u00a1-\uffff]{2,})))(?::\d{2,5})?(?:\/[^\s]*)?\z/i
 validates :website, format: { with: WEBSITE_REGEX }, if: 'website.present?'
 validates :industry, presence: true
 validates :user_id, presence: true
end

但是当我打开de rails console并输入以下内容时:

project = Project.last
#returns project
project.notifications.build(icon: "icon.jpg", text: "lorem ipsum")

我收到以下错误:

NoMethodError: undefined method `notifications' for #<Project:0x00000005916ef0>
Did you mean?  notifcations

2 个答案:

答案 0 :(得分:1)

是的,你应该改为:

Project
  has_many :notifications # not :notifcations

答案 1 :(得分:1)

请更新您的拼写并再次查看相同内容。

class Project < ActiveRecord::Base
 belongs_to :user 
 has_many :notifications
 before_save :set_start_date

仔细阅读错误

NoMethodError: undefined method notifications for #<Project:0x00000005916ef0> Did you mean? notifcations