Rails - Create if record doesn't exist or else update.....Whats Best way to do this?
Posted
by
ChrisWesAllen
on Stack Overflow
See other posts from Stack Overflow
or by ChrisWesAllen
Published on 2011-01-06T23:44:37Z
Indexed on
2011/01/06
23:54 UTC
Read the original article
Hit count: 164
Hi,
I have a create statement for some models but its creating a record within a join table regardless if the record exist. Here is what my code looks like.
@user = User.find(current_user)
@event = Event.find(params[:id])
for interest in @event.interests
@user.choices.create(:interest => interest, :score => 4)
end
The problem is it creates records no matter what. I would like it to create a record if it doesnt exist, if a record does exist I would just to it to take the attribute of the found record and add or subtract 1. So, I've been looking around and I see something called find_or_create_by. My question is what happens if it finds? Preferably if it finds,I would like to take the current :score attribute and +1.
SO is it possible to find or create by id? I'm not sure what attribute I would find by since the model I'm looking at is a join model which only had id foreign keys and the score attribute.
I tried
@user.choices.find_or_create_by_user(:user => @user.id, :interest => interest, :score => 4)
but got "undefined method `find_by_user'".....ANy ideas or help?
© Stack Overflow or respective owner