Jon
Jon

Reputation: 129

Rails: attributes not being saved even though I called @user.save

I'm running this function, and I KNOW that it gets called because the redirect_to is working. But for some reason, @user isn't! If it helps, @user is devise based.

def make_feed_preference
@user = current_user
#@user.feed_preference = params[:preference]

@user.feed_preference = "time"
@user.name = "Shoo Nabarrr"
@user.karma = 666

@user.save

redirect_to '/posts'

end

I fixed it myself. I had to create a new class attached to users in order to get it to work. Lol.

Upvotes: 2

Views: 244

Answers (2)

Jeremy Weathers
Jeremy Weathers

Reputation: 2554

There are cases where I want to be sure to update a flag or other field on a record even if the record has validation problems. (However, I would never do that with unvalidated user input.) You can do that thusly:

def make_feed_preference
  case params[:preference]
  when 'time', 'trending_value', 'followers'
    current_user.update_attribute 'feed_preference', params[:preference]
    flash[:notice] = 'Your feed preference has been updated.'
  else
    flash[:notice] = 'Unknown feed preference.'
  end
  redirect_to '/posts'
end

Upvotes: 0

Ryan Bigg
Ryan Bigg

Reputation: 107728

Do you have any validations on this user? They are probably blocking this save. The redirect_to will be called regardless of whether or not the save passes or fails.

I would recommend doing it like this instead:

if @user.save
  redirect_to '/posts'
else
  render :feed_preference
end

Where :feed_preference is the form where users enter their feed preferences.

Upvotes: 2

Related Questions