0

I have 3 different partials and want them displayed in the view at different places depending on the exact product (or record in the database). On a few products, I only want to display 2 of the 3 partials. How would I accomplish this? Thank you.

3
  • I am not sure if this requires JS or CSS or if there is a rails solution. I have not tried anything but been looking for a good way to accomplish this. Commented Sep 8, 2016 at 19:15
  • Since you want to display partials in the view depending on the exact product (or record in the database) you have to use rails. You can use controller methods for this. Commented Sep 8, 2016 at 19:18
  • There are quite a few combinations. What would a controller method look like? Just a case statement? Commented Sep 8, 2016 at 19:20

1 Answer 1

2

Assuming you have some template, say products/show.html.erb, which you want to render your partials with your custom logic, I'd suggest just embedding your conditional logic into that template. Here's an example with a lot of assumptions made on my part; feel free to add more details and I can update.

First, your primary template, which I'm assuming is your show action:

# products/show.html.erb

<h1>Product <%= @product.name %></h1>
<p><%= @product.description %></p>

<% if @product.is_fungible? %>
  <%= render partial: 'products/fungible', locals: { product: @product } %>
<% end %>

<% if @product.is_edible? %>
  <%= render partial: 'products/edible', locals: { product: @product } %>
<% else %>
  <%= render partial: 'products/inedible', locals: { product: @product } %>
<% end %>

And your partials might look like so (note that, since we've passed in product as a local variable, we don't need to use the instance variable @product in them:

# products/_fungible.html.erb

<p>This product is definitely fungible, by a factor of <%= product.fungibility %>.</p>
Sign up to request clarification or add additional context in comments.

1 Comment

That is one solution that works. I also found that I can use the specify the partial as a variable and with that variable referring to the template. <% render partial => product.partialone %> for example where product.partialone is "products/edible".

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.