开发者

Rails won't save boolean "hidden" value but saves other values

开发者 https://www.devze.com 2023-01-24 01:12 出处:网络
I\'m a little new to Rails, and I have a simple app with some stories. I want to have this function to easily hide stories I don\'t want to appear right now. Other functions set up the same way work f

I'm a little new to Rails, and I have a simple app with some stories. I want to have this function to easily hide stories I don't want to appear right now. Other functions set up the same way work fine, except this one with the boolean value.

  def hide
    @story = Story.find(params[:id])
    @sto开发者_运维问答ry.hidden = true

    if @story.save
      redirect_to :controller => 'pages', :action => 'home'
    else
      redirect_to :controller => 'stories', :action => 'show', :id => @story.id
    end
  end

For some reason when this function runs it doesn't update the "hidden" attribute of the Story, but @story.save returns true (it does the first part of the if statement). Am I doing something wrong to set @story.hidden = true? I'm using sqlite, if that matters. Thanks!


If this will just be updating a boolean attribute always to true then you can do it like this:

def hide
    @story = Story.find(params[:id])
    @story.update_attribute(:hidden, true)
    redirect_to :controller => 'pages', :action => 'home'
end


Well, firstly, why are you using a custom action? This should go into the update action in the controller and you should be passing the boolean through the form.

Now, for your specific question, check if the @story variable has modified the object, but doing this:

logger.debug @story.changed?

If this returns true, it means that the record should be updated and you should be looking at the log to ascertain what the UPDATE statement really is. You should probably post that back here.


Use update_attributes! : it will not skip validation and will throw an exception on errors.
Also consider using rescue, since the Story.find() as well as update_attributes! can fail.

def hide
  @story = Story.find(params[:id]).update_attributes!(:hidden => true)
  redirect_to :controller => 'pages', :action => 'home'
end
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号