Reputation: 385
I have got the following problem
My edit function saves the model object with the id 33 as the id 32, and i dont know why. here's my controller function:
def update
@user = User.find_by_id(session[:user_id])
@user.ranks[0].update(user_params)
redirect_to dashboard_ranks_path
end
private
def user_params
params.require(:rank).permit(:points, :rank_name, :id)
end
The same method works on another controller but on this one it suddenly doesnt work for some reason. for example I have got 3 posts, I edit the first one, it does not change the id and it will edit itself successfully. However if I chose the second one it choses the id of the third one, if i edit the 3rd one it somehow patches the first one. Did anybody had a bug like that before?
Upvotes: 2
Views: 66
Reputation: 76784
You're getting the error because you're not using the rank id
variable...
@user = User.find_by_id session[:user_id]
@user.ranks[0].update user_params #-> how do you know which rank is first?
redirect_to dashboard_ranks_path
You'll be better doing the following:
@user = User.find session[:user_id] #-> find uses id anyway, and even then "find_by :attribute" is the `Rails 4` way of doing it
@rank = @user.ranks.find params[:id]
@rank.update user_params
This will select the rank
based on the pased params[:id]
variable which you've passed through your route:
/ranks/edit/33
Upvotes: 1
Reputation: 2844
Do you have multiple servers running your application? Are you using a database/redis backed session store? Particularly, the way you get the rank through the user association seems to be the problem. Ideally you would do something like
rank = @user.ranks.find_by_id params[:rank][:id]
rank.update(user_params) if rank
Not relevant to the issue, but I'd suggest changing the name of user_params, to rank_update_params or something that does represent what they are for.
EDIT
The two first questions are relevant to know if the user that owns the rank you are editing is the same you are accessing from the session.
Upvotes: 2