I am getting a “NoMethodError in ProjectsController#create” with the following code:
def create
@project = current_user.project.build(params[:project])
if @project.save
flash[:success] = "Project created!"
redirect_to root_url
end
end
I have tried using @project = current_user.project.create(params[:project]) as well, but I get the same error, albeit for .create.
My Project model looks like this:
class Project < ActiveRecord::Base
attr_accessible :title,
:sub_title,
:desc,
:category
validates :user_id, presence: true
validates :title, presence: true, length: { maximum: 35 }
validates :category, presence: true
belongs_to :user
...
end
and my User model looks like this:
class User < ActiveRecord::Base
attr_accessible :name,
:surname,
:email,
:email_confirmation,
:password,
:password_confirmation
has_secure_password
has_one :project
...
end
From what I can tell, this should create a new Project with an association to the user.id and project.user_id. Any ideas why I get the error instead of successful creation?
For
has_oneassociations you want:The same pattern is used for create:
If you look at the has_one documentation they list the methods that get created when you declare the association.