1

Say for example I have two models, posts and category. Now say I want to make it so the from the category show page you can create a new post using the form_for method. To do this, you will obviously need access to the @category variable and a new instance of a post (@post). Is this acceptable code in the controller?

#app/controllers/categories_controller.rb
def show
  @category = Category.find(params[:id])
  @post = Post.new
end

Or is it bad practice to have two instance variables defined in the one controller action - and if it is, what would be the best practice for a case like this?

1
  • How are Post and Category related? Could you show that as well? Commented Apr 2, 2015 at 3:14

2 Answers 2

2

I usually do something like:

#app/controllers/categories_controller.rb

helper_method :category
helper_method :post

def show
end

private

def category
  @_category ||= params[:id] ? Category.find(params[:id]) : Category.new(params[:category])
end

def post
  @_post ||= Post.new(params[:post])
end

Then, in your views, just refer to post or category (not @post or @_post). The nice thing is you can remove the same logic from your new, delete, etc methods...

Sign up to request clarification or add additional context in comments.

Comments

0

Actions related to posts should be in the PostsController as much as possible.

Let's say the user is looking at all posts under the category "rails": /categories/rails

There's a button on that page to create a new post under the "rails" category, href: /posts/new?category=rails

This takes you to PostsController#new where you instantiate a new Post, validate the category param and build a view. This view could either be a new page, or a modal popping up.

2 Comments

I don't necessarily agree with this. Although it might be a "best practice" there are definitely times where you might want to do it like OP is doing, such as replying to a forum thread via a quick reply box. It depends on the situation.
@Jake0oo0 Yes I probably should have elaborated that I was doing a modal popup here and wanted to know if this still was the best way to go about it

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.