Harazzy
Harazzy

Reputation: 201

Having multiple instance variables in rails controller action? (Rails best practices)

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?

Upvotes: 1

Views: 1213

Answers (2)

Brad Werth
Brad Werth

Reputation: 17647

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...

Upvotes: 2

Rahul
Rahul

Reputation: 1876

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.

Upvotes: 0

Related Questions