Joshua
Joshua

Reputation: 83

How to use same partial with variables from different controllers?

In my application, users submit reviews under brands. Here's the association:

class Brand < ActiveRecord::Base
has_many :reviews

class Review < ActiveRecord::Base
belongs_to :brand

Right now I have a partial defined to show reviews as such:

_showreview.html.erb

<% review.each do |review| %>
<div class="col-sm-4">
<div class="thumbnail">
<%= image_tag review.first_photo %>
<div class="caption">
<h4><%= link_to review.title, review %></h4>
<h6><strong><%= link_to ("WRITTEN BY " + review.user.username.upcase), review.user %></strong></h6>
<%= review.description.truncate_words(60, omission: '...') %>
<br>    
<br>
<%= link_to review.brand.label, review.brand, :class => 'btn btn-sm btn-lake' %>
</div>
</div>
</div>

And I render it like this by passing an instance variable in:

<%= render "showreview", review: @top_reviews %>

It works as expected.

Now I wish to reuse the partial for brands/show.html.erb

What I want to do now is retrieve all the reviews that belong to a brand and display it.

show_controller.rb looks like this

 def show
  @brand = Brand.find(params[:id])
 @reviews =Review.find(params[:id])
 end

I tried to use this but it doesn't work. What is the correct way to do this?

<%= render "/reviews/showreview", review: '@brand.reviews' %>

Upvotes: 0

Views: 67

Answers (3)

thanh do
thanh do

Reputation: 5

firstly, you should use a plurality for the variable review instead.

reviews.each do |review|

it makes your code readability. then try placing review: '@branch.review' by reviews: @branch.reviews and make sure that you did pass the variable @branch from your controller

Upvotes: 0

Vishal
Vishal

Reputation: 7361

Your method will be like this

def show
  @brand = Brand.find(params[:id])
end

and in your view

 <%= render "reviews/showreview", review: @brand.reviews %>

Upvotes: 0

Alex Kojin
Alex Kojin

Reputation: 5204

<%= render "/reviews/showreview", review: @brand.reviews %>

But please, rename review to reviews. It's more convenient name of this variable.

Upvotes: 2

Related Questions