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.
-
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.Joe D– Joe D2016-09-08 19:15:19 +00:00Commented 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.luissimo– luissimo2016-09-08 19:18:19 +00:00Commented Sep 8, 2016 at 19:18
-
There are quite a few combinations. What would a controller method look like? Just a case statement?Joe D– Joe D2016-09-08 19:20:32 +00:00Commented Sep 8, 2016 at 19:20
Add a comment
|
1 Answer
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>
1 Comment
Joe D
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".