Reputation: 140
I'm having a lot of trouble getting associations to work in Rails 4.2.2. I have a project and this project can have lots of notifications. What I would like to have is that I can add notifications with:
@project.notifications.build(icon: "icon.jpg", text: "lorem ipsum")
So I have added belongs_to to the Notification model I've created, which you can see below:
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
And added the has_many association to the Project model:
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
But when I open de rails console and go enter the following:
project = Project.last
#returns project
project.notifications.build(icon: "icon.jpg", text: "lorem ipsum")
I get the following error:
NoMethodError: undefined method `notifications' for #<Project:0x00000005916ef0>
Did you mean? notifcations
Upvotes: 0
Views: 70
Reputation: 4780
Please update your spelling and check back again for the same.
class Project < ActiveRecord::Base
belongs_to :user
has_many :notifications
before_save :set_start_date
Read the error carefully dear
NoMethodError: undefined method notifications for #<Project:0x00000005916ef0> Did you mean? notifcations
Upvotes: 1
Reputation: 5623
Yeah, you should change to:
Project
has_many :notifications # not :notifcations
Upvotes: 1