I am currently creating a web page with Rails.

We are currently coding as follows, and before rendering a certain page, we put the data narrowed down by the condition from the table into @posts and use it in show.html.erb.

When a certain button is pressed on that page, the POST process is performed and the xxxx method is called, but when saving to the table, it passes validation, and if it succeeds, it redirects, and the error content on failure It is a flow of passing and re-rendering.

After processing the current error, @posts is not passed just before rendering, so an error has occurred.
Is it possible to reuse the @posts passed during the show for the @posts passed here?

In that case, pass all the search conditions for where
@posts = Post.where (Filter by various conditions depending on parameters)
Will it be a flow to write again?

Because this page performs post processing in various places, you have to write a lot of this processing after error validation, so I thought it would be nice if you could easily reuse @posts from a previous show. It was.

It can be a useful site, so please let me know the appropriate method.
Thank you.

def show
   @posts = Post.where (Narrow down by various parameters)
   render 'homes/show'
def xxxx
   @aaaa = XXXX.new (name: xxx, yyy: params [: yyy], zzz: params [: zzz])
   if @ aaaa.save
      redirect_to controller: 'homes', action: 'show'
       # Error handling
       # I want to use @posts here with the same conditions as the one passed in show
       # Do I have to pass the same parameters as the search condition when posting and do the following again?
       # @posts = Post.where (Filter by various conditions depending on parameters)
      render 'homes/show'

# show.html.erb
<% @ posts.each do | post |%>
  Various processing
<% end%>

Amazon Linux release 2 (Karoo)
Rails 5.2.3
Ruby version: 2.6.1

  • Answer # 1

    You cannot reuse @post.
    Instance variables starting with @ can only be used within that instance. It is possible to make it accessible from outside the instance, but it disappears when the instance runs out.
    An instance of the controller is created by a request from the browser and will disappear when the request is answered. Requests made with show disappear when show output ends, so @post is also gone.