简体   繁体   中英

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?

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM