RESTful membership - ruby-on-rails

I am currentlly trying to design a RESTful MembershipsController. The controller action update is used only for promoting, banning, approving,... members. To invoke the update action the URL must contain a Parameter called type with the appropriate value.
I am not too sure if that is really RESTful design. Should I rather introduce sepearate actions for promoting,... members?
class MembershipsController < ApplicationController
def update
#membership= Membership.find params[:id]
if Membership.aasm_events.keys.include?(params[:type].to_sym) #[:ban, :promote,...]
#membership.send("#{params[:type]}!")
render :partial => 'update_membership'
end
end
end

Neither. The only "actions" a controller should handle are GET, PUT, POST, DELETE (+other http verbs). I realize posting this on a question tagged with "rails" is heresy but today I don't care.
One RESTful way to do this is to create new "processing resources" for each of these operations and POST the member to that resource to invoke the action.
When I say create a new resource, you can interpret that to mean, create a new controller.

To me this is one of the cases when you just shouldn't pull your hair out in efforts to adhere to REST conventions. Your model doesn't seem to fit in with the traditional CRUD concept, and the RESTful principle of differentiating actions via HTTP verbs doesn't seem to belong here too.
If I were you, I would split that action into separate actions for what you need to do with your memberships (trying to stay as DRY as possible). That would make the controller code more readable. And by creating some routes I would also make the view code cleaner (promote_membership_path, etc.). But that's just me :), so see what fits most for you.
EDIT:
here is an article which explains my point of view a bit: http://www.therailsway.com/2009/6/22/taking-things-too-far-rest

Well, there is more than one way to do things. The questions you should be asking yourself, is how many states are there? How often do new states get added? Etc.
If there wouldn't be that many states, I would create separate actions + a before filter for the find, but I think this is more of a personal preference. If you really want to keep it short, you can put each method on one line. So:
class MembershipsController < ApplicationController
before_filter :find_membership
def ban; #membership.ban!; render :partial => 'update_membership' end
def promote; #membership.promote!; render :partial => 'update_membership' end
protected
def find_membership
#membership = Membership.find(params[:id)
end
end
To answer your question whether it is RESTful: yes, your update method is perfectly RESTful, but remember that a PUT should be idempotent. So if I execute the same method twice, is the result the same? i.e. what happens if I ban a user and ban him again?

Related

Ruby on Rails RESTful controller function order

I'm pretty new to rails and have been going through the process of building a REST service. In the rails guide it seems pretty specific when they tell you where in the controller class to add their functions: create after new, show before new, etc. I guess I was just curious if there is some convention that most people use for ordering (when I rake routes the order is: index, create, new, edit, show, update, destroy). Not that its a big deal as long as your project is consistent, but is there a "conventional order" that people use? If not, I guess we could all argue about who's order is better.
Thanks!
The order of controller actions isn't really important at all, but I generally follow the same convention that Rails uses in it's own scaffolded controllers.
This way, I can easily scan to the controller action I'm looking for when I open a controller file.
Index, Show, New, Edit, Create, Update, Destroy
I think this order makes sense, as index and show are both concerned with "Showing" or "Reading" data, a primary concern in a web app.
Then new and edit, and create are concerned with "Creating", so they should be grouped together.
After create is update, which are usually very similar.
Then there's destroy, which is usually very simple and the only action of it's kind.
When adding custom actions to a controller, I keep them near the action they are most like, in terms of interactions.
If I have a method that is to display a subset or collection of things, I'll put it under index. If I have actions to upvote or downvote things, I think those fit nicely under update, since they are updating some part of the record.
Totally a personal decision but I do have a way that I set up my controllers:
def index end
def show end
def new end
def create end
def edit end
def update end
def destroy end
# non-restful endpoints/actions
For me, I like new/create and edit/update together since they, essentially, fire one after the other (when you are on the edit view, you're typically going to update the record, etc.).
Ultimately, I think having a system that works for you that you can follow and stay with is most important.

Rails: Is it bad practice to handle CRUD operations for two models in one Controller?

I am working on a Rails project. I was advised to make one controller, the Home_Controller, which would handle the requests of the site. I have two different models, Post and Person (which btw are totally independent). I would like to define methods like new in the Home Controller but it seems against convention to write controller methods like new_person and new_post.
Thanks for your help!
It IS against the MVC pattern, as your Home_Controller should only control the Home model.
You should have a PeopleController and a PostsController to separate your concerns.
That being said - it's not totally unheard of to have the system that you are asking for.. You'll just have to create your own custom routes in routes.rb to match what you want. For example, your HomeController could look like,
class HomeController < ApplicationController
...
def new_person
#person = Person.create
end
def new_post
#post = Post.create
end
end
Routes would look something like,
get 'people/new' => 'home#new_person'
get 'post/new' => 'home#new_post'
the main issue is that when you stray away from this convention, you run into very unreadable and hard to maintain code. especially when you have multiple hands in 1 file.
Going to go ahead and say probably. It's hard to know exactly outside of context, but yes, this would go against convention.
Separate from the convention issue, is maintainability and readability and having one massive controller file would be hell to develop on.

Ruby on Rails Controller methods separately?

Just to be educated I wanted to know if it is a good practice to have one controller method for both GET and POST actions, e.g def signup ... end, which would display a form and if request.post? is true - then perform all the business-logic and so on. Is it any good approach, or should I have these methods being separated from each other ?
Thanks in advice!
I think it'll be much better to define a separate action for the post request. You can obviously get it done within the same action, but if you're going to write a big if..else block in sign_up action you may as well use another action. You could call it create if you're short of names :P . It makes the code more logical and readable.
There is little difference in code organisation either way.
With separate methods, it looks like:
def signup_create
# create here
end
def signup_new
# render here
end
With the same method, it looks like:
def signup
if request.post?
# create here
else
# render here
end
end
It looks like they are both reasonably well organised. Choose what your prefer. If they are the default CRUD methods, separate methods are nice, given that there are separate names thought up already (eg. new vs create, edit vs update).
If they are not CRUD, or extra forms on the page, and you can only think of one name for it (like signup), feel free to overload the name and use the same method.
i think that separate actions for different requests are better if u are using(or going to use) method based authorization (eg cancan).

Trash implementation in rails app

In my app I'm trying to implement trash for some objects, i.e. there will be column "trashed" and it'll set to date, when the object was trashed. Trash also has an index page, where users can restore objects - set "trashed" to nil.
I found examples of models with method trash!, that set trashed to date and it was implemented with Concerns. But I don't really understand how to implement controllers with action to_trash? Is there any way to use Concerns with controllers too or every controller should have it's own action and route for calling it?
Now I implemented it with controller Trash, that have action move_to_trash and every controller use this action, but I have to add get params trashable_id and trashable_type to do this. Is it a good way to do things?
I think the simplest implementation could be to add to your routes.rb file the following:
match ':controller/:id/trash', :action => :trash
This will allow you to use the action trash on every controller. Have a look at the Routing Rails Guide for more examples.
A simple implementation is the following (taking the model Report as example). I don't use Concern here:
class ReportsController < ApplicationController
def trash
#report = Report.find(params[:id])
<Do the trashing of report here, you know that already.>
# Decide what to do after having called #trash
respond_to do |format|
format.html { redirect_to(reports_url) }
end
end
end
If you have only some controllers that should allow the action, it is perhaps easier to add special routes rules for each controller, instead of adding it to every one. And if you want to go a step beyond, you may implement the trash action in a mixin, and mix it in the controller you want to have it in (and no, I don't will implement that, too).

How do I determine the default action for a Rails controller?

I'm working on a functional test that needs to assert that a certain XHTML tag is present in a certain set of controllers. I'm basically doing this:
class ApplicationControllerTest < ActionController::TestCase
def setup
#controller = ApplicationController.new
end
# [...]
def test_foo_bar_and_baz_include_stylesheet
[FooController, BarController, BazController].each do |controller|
#controller = controller.new
get :show
assert_select 'head > link[rel="stylesheet"]'
end
end
end
The problem is that not all controllers have a :show action. What I need to do is ask either the controller or the routing configuration for the controller's default action and call get with that.
Update: Joseph Silvashy was right: I ended up separating my controller gets out into separate test cases. Solving the "default" route problem was bad enough, until I discovered that some of my routes had conditions attached, and I would have to parse them to craft the correct get call. And finally, Rails functional tests don't deal very well with calling get multiple times in the same test case, especially when that those calls are hitting multiple controllers. :(
I think the lesson here is one that we all know by heart but sometimes is hard to accept: if the code looks hairy, you're probably doing it wrong. ;)
Controllers don't have a "default" view or action, additionally actions can be named anything you want, they don't have to be the standard index, show, new, etc...
I'll probably have to :get the appropriate action for each controller you want to test. It's likely each test will be different down the road anyhow, even though right now they all have the same requirement, I think it makes sense to write one for each action regardless.
try to use the respond_to function: http://www.ruby-doc.org/core/classes/Object.html#M001005
to check if a method exitst.

Resources