0

Here is my question. I basically have Controller A. What I want to do is display the index action of Controller B within the index view of Controller A.

I did this by making a new partial where I put my code snippet. I then rendered the correct partial and it gave me undefined variable errors. The only way I fixed it was by making an instance variable that included all of the instances of that model object. It works! But...is this the correct way to do it? Making an instance variable with all of the records seems that clumsy.

This is the index view of my Controller A. "Monthly_Challenges" is my Controller B.

<%= render "monthly_challenges/index"  %>

<br>

Here is my partial. Note line 1, is that right?

<% @monthly_challenge = MonthlyChallenge.all %> #this seems not good
<p>
  <strong>Name:</strong>
  <%= @monthly_challenge.name %>
</p>
1
  • There's something that goes like = render partial: "monthly_challenges/index", monthly_challenge: @monthly_challenge that you can use to include partials. That way you only have to initialize the variable at the first controller. Not sure if that's what you're looking for. You can use the variable monthly_challenge in the partial that way. Commented Mar 5, 2015 at 4:36

2 Answers 2

3

Just put this line

@monthly_challenge = MonthlyChallenge.all

in the index of your A controller :

def index 
  @monthly_challenge = MonthlyChallenge.all # from controller B
  #rest of code for controller A
end

Then in your view

<p>
  <strong>Name:</strong>
  <%= @monthly_challenge.name %>
</p>

MonthlyChallenge is a model and can be instantiated in any controller.

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

Comments

1

there's no reason why your Controller A cannot marshal up instances of MonthlyChallenge. I'd recommend that keeping data marshaling out of the views is a Good Thing.

From the home page of one of my projects:

def index
  @projects = Project.find(:all, :limit => 5, :order => 'updated_at DESC')
  @scenarios = Scenario.find(:all, :limit => 5, :order => 'updated_at DESC')
  @unittests = Unittest.find(:all, :limit => 10, :order => 'updated_at DESC')
end

The index view just renders 3 partials, one for each type of model marshalled.

Comments

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.