Teresa
Teresa

Reputation: 373

Ruby on Rails: Passing a variable to a partial that can be of different classes

Note: Apologies if this is a duplicate, I couldn't find an answer. Warning: Newbie to RoR, the answer is probably incredibly obvious.

I have a partial, _show_address_on_map, which shows the location of a person on a map. However, this person can be an @employee or a @client, and can be called from the employee_addresses controller or the client_addresses controller. Depending on which of the two it is, some things need to be changed within the partial.

In employee_addresses/show.html.erb I call the partial with

<%= render :partial => ".../show_on_map", currentUser: @employee %>

In client_addresses/show.html.erb I call the partial with

<%= render :partial => ".../show_on_map", currentUser: @client %>

Now in the partial (_show_address_on_map) I try to do an if-statement on currentUser:

<% if currentUser.is_a?(Client) %>
    #do something with @client
<% else %>
    #do something with @employee
<% end %>

This gives me the error "undefined local variable or method 'currentUser'"

How do I correctly define currentUser, so that it can be either @employee or @client as described? Or am I doing something else wrong?

Upvotes: 1

Views: 238

Answers (2)

Alejandro Montilla
Alejandro Montilla

Reputation: 2654

You can use the :object to send a data into the partial, and that will define a variable with the same name as the partial

<%= render :partial => ".../show_on_map", :object => @client %>

So in your partial, you can reference the :object send with the name of the partial _show_address_on_map, you can do something like this:

<% if show_address_on_map.is_a?(Client) %>
    #do something with @client
<% else %>
    #do something with @employee
<% end %>

And that will contain the @client sent in :object, so you can control what action do in the partial.

Upvotes: 1

Ruslan
Ruslan

Reputation: 2009

<%= render :partial => ".../show_on_map", locals: {current_user: @client}%>

:)

Also as a ruby/rails convention, use the under_score rather than camelCase

Upvotes: 4

Related Questions