Search code examples
ruby-on-railsmodel-view-controllercontroller-actions

Best practice for controller actions for changing state of model


I have a controller with the normal CRUD actions for a resource called "Issue". The Issue table has a boolean called published to save the state of each instance. When an issue gets the published boolean set to true, all the other instances of Issue should be set to false.

My question is about the issues_controller.rb. Right now, I don't have the published boolean listed as attr_accessible. My thought was that I would have a button in my view that routed to a specific action:

def publish
  // before_filter to set all the issues' publish column to false
  // update_attribute to set publish column to true
end

def surpress
  // update_attribute to set this issues publish column to false
end

After doing some research and rethinking my approach, I thought perhaps it would be better to create some sort of new controller - published_issues_controller.rb that uses more resourceful routes:

def create
  // same as the publish method above
end

def destroy
  // same as surpress method above
end

This is my first rails app - any insight on whether one of these approaches (or something completely different) is best would be much appreciated.


Solution

  • When an issue gets the published boolean set to true, all the other instances of Issue should be set to false

    That seems like a strange business requirement to me?

    Anyhow, I would use the controller actions you have documented, but would not use the before filter

    # routes
    resources :issues do
      member do
        post 'publish' # might want put instead of post?
        post 'surpress' 
      end
    end
    

    Controller

    def publish
      issue = Issue.find(params[:id])
      Issue.transaction do
        issue.publish!
      end
      # ... redirect, etc...
    end
    

    Model

    def publish!
      published = true
      # set 'All' other issues [published = false]
      # maybe it is only ones that are somehow related to this one? same project?
      save!
    end