0

I'm stuck trying to access instance variables from one controller/view to another.

ProductsController

def index
  @searcher = build_searcher(params.merge(include_images: true))
  @products = @searcher.retrieve_products
end

I want to gain access to @products in _header.html.erb partial, which is a part of the main layout page application.html.erb.

3
  • Which local variable are you having problem with? I don't see any. Commented Mar 7, 2019 at 10:10
  • My fault. Instance variable Commented Mar 7, 2019 at 10:17
  • @pfc And what if you render header for some other action, where @products is not defined? Commented Mar 7, 2019 at 15:54

1 Answer 1

1

It's always a good practice to pass local variable inside a partial, to make it useable at more than one place. so you should pass @products inside a local variable in partial -

Unless i'm missing something variable should be @products instead of @product as index action has @products

= render partial: 'header', locals: {product: @product}

In _header.html.erb product local variable will be accessible which is @product

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

1 Comment

Let me reformulate question(maybe you haven't seen edit). I want to gain access of INSTANCE variable @products from products controller, index action. I need that in my _header partial view which is part of main layout of page

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.