I have a bit of an odd issue. I have a projects controller where I am creating a new project related to a company and created by the logged in user (current_user), here is my create action.
def create
@project = @company.projects.build(params[:project].merge!(:user => current_user))
#@project.user = current_user
if @project.save
#debugger
flash[:notice] = "Project has been created."
redirect_to [@company, @project]
else
flash[:alert] = "Project has not been created."
render :action => "new"
end
end
The above code breaks on the redirect to the project show page with the following error:
undefined method `email’ for nil:NilClass
%b
Created by
= @project.user.email # <-- errors, not sure why
So I know everything else is saving except the user who created that project. If I remove the .merge! in my create method and do it in two steps it works perfectly fine, like so:
def create
@project = @company.projects.build(params[:project])
@project.user = current_user
....
How come using merge! would not work? I would have thought that merging the user into the object would be perfectly fine. What is the right (or preferred) way to go about this?
Thanks
I’ve figured it out. It was a mass assignment issue. I had
attr_accessible :title, :description, :account_number, :account_executivein my code, disabled it to allow mass assignment and it worked fine.