1

I am trying to play with Rails naming conventions as in here and render two different pages with different variables using one partial.

index

<%= render @events_future %>

current

<%= render @events_current %>

event controller

def index
  @events_future = ...
end

_event.html.erb

<% @events.each do |event| %>
...
<% end %>

I get the undefined "each" method Please point me in the right direction

3 Answers 3

1

I think the best thing to do here is to pass a locals to the partial _event.html.erb because the partial needs to display different objects like follows:

index

<%= render 'event', events: @events_future %>

current

<%= render 'event', events: @events_current %>

In the above two render statements, the events gets passed to the event partial as a local.

Then in your _event.html.erb you would do:

<% events.each do |event| %>
...
<% end %>
Sign up to request clarification or add additional context in comments.

Comments

0

Do you have @events initialized in your controller?

I see that you have @events_future and @events_current, but if @events is not defined in the controller, your view wouldn't know what you are referring to.

If you want to reuse events for both future and current, use the following in each view

<!-- index.html.erb -->
<%= render 'event', events: @events_future %>

<!-- current.html.erb -->
<%= render 'event', events: @events_current %>

This renders the _event.html.erb partial and sets the events local variable. In _event.html.erb, use

<% events.each do |event| %>
  <!-- do stuff -->
<% end %>

1 Comment

No I do not have @events initialised, but got it all working (see answer above)
0

You have to pass the variable to the partial when you render it:

render :partial => 'event', :locals => {:events => @events_current} %>
render :partial => 'event', :locals => {:events => @events_future} %>

And then in your partial you do:

<% events.each do |event| %>
...
<% end %>

1 Comment

Okay I delete my comment then ;)

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.