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

独自空忆成欢 提交于 2019-12-24 04:16:07

问题


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.


回答1:


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.




回答2:


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


来源:https://stackoverflow.com/questions/7265009/rails-attributes-not-being-saved-even-though-i-called-user-save

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!