Lush
Lush

Reputation: 282

In Rails, is there anything 'wrong' with creating a custom controller action for a view that has both 'index' and 'new' functionality?

I'm creating a simple application where the user can view to-do list items and add new ones. In tutorials, the design is usually the same:

This doesn't seem like a very good user experience for such simple functionality. I'd like to have the to-do items listed at top (the 'index' part), and on the same page, have a form at bottom to add new to-do items (the 'new' part).

Now that I have two CRUD functionalities on the same page ('index' and 'new'), what would the route be since it's a hybrid of 'index' and 'new'?

It seems to me like I will have to have a custom controller action and view if I want to have multiple CRUD functions on the same page. Is that right, and is there anything wrong with that?

Upvotes: 0

Views: 78

Answers (2)

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230356

is there anything 'wrong' with creating a custom controller action for a view that has both 'index' and 'new' functionality?

Yes, it is wrong to create a custom action for this.

On the other hand, putting a form for new element on index page is perfectly fine. CRUD stands for Create,Read,Update,Delete. "new" action is not part of this. It is merely a necessary crutch (you need something to render that form). If you don't want a separate page, have the form right on index page.

Same with edit. If you, for some reason, don't want a separate edit page, you can implement inline-editing. You can see this functionality in many apps.

Upvotes: 1

Vlad Balanescu
Vlad Balanescu

Reputation: 674

There is no problem at all having your own method in todo_controller.rb, but you will need to add:

match '/todo', to: 'todo#hybridMethod', via: [:get, :post]

And then you will have to have your own view which have to match the method name, in my example hybridMethod.html.erb under app/views/todos. You can copy the code from index and new methods into your new hybridMethod, but don't forget to leave create in place, as after you fill in the form the data will get sent to create method which will add the entry in the db and redirect if successful. It is not Rails way of doing it, but you can break the rule in this case. I really hope this answers your question!

Upvotes: 0

Related Questions