[Help] Need help with first_or_create. Never finds existing Record

16 views
Skip to first unread message

Chris Maher

unread,
Oct 30, 2015, 5:40:08 PM10/30/15
to rubyonra...@googlegroups.com
I have a problem with a form that either updates or creates depending on
whether the "project" exists already.

Im using the def create

def create
puts params.inspect
@project = current_user.projects.where(id:
params[:id]).first_or_create(project_params)
puts params.inspect
if @project.save
flash[:success] = "Project created!"
redirect_to root_url
else
flash[:success] = "Project not created!"
redirect_to root_url
end
end

Problem is it never finds the existing record.

generated SQL is


SELECT "projects".* FROM "projects" WHERE "projects"."user_id" = ? AND
"projects"."id" IS NULL ORDER BY "projects"."created_at" DESC LIMIT 1
[["user_id", 1]]
Im sending the parameters in wrong but i'm not sure of the solution.

--
Posted via http://www.ruby-forum.com/.
Message has been deleted

James Davis, PhD

unread,
Nov 1, 2015, 7:47:35 AM11/1/15
to Ruby on Rails: Talk
Yeah the sql you posted will not work.
First, find the record with @project = current_user.projects.where(id:
params[:id]).first_or_initialize and then set the attributes as desired.

Frederick Cheung

unread,
Nov 2, 2015, 6:04:53 AM11/2/15
to Ruby on Rails: Talk


On Friday, October 30, 2015 at 9:40:08 PM UTC, Ruby-Forum.com User wrote:
I have a problem with a form that either updates or creates depending on
whether the "project" exists already.


How do you want to determine whether the project exists or not?
 
Im using the def create

def create
    puts params.inspect
    @project = current_user.projects.where(id:
params[:id]).first_or_create(project_params)

[snip] 

Problem is it never finds the existing record.

generated SQL is


SELECT  "projects".* FROM "projects" WHERE "projects"."user_id" = ? AND
"projects"."id" IS NULL  ORDER BY "projects"."created_at" DESC LIMIT 1
[["user_id", 1]]

This shows that params[:id] was nil. Were you expecting that? 

Fred 
Reply all
Reply to author
Forward
0 new messages