Question

I have my show action as below:

def show
  @car = Car.friendly.find(params[:id])
  @cars = @car.other_cars_in_showroom
end

My Car model with appropriate method is:

def other_cars_in_showroom
  cars = self.showroom.cars
  cars.delete(self)
  cars
end

My issue is, the above works and the page renders fine, however, after a page refresh I get:

undefined method `cars' for nil:NilClass

The error is on the self.showroom.cars line. How can I resolve this? All I require is to retrieve a list of all other cars in the same showroom as @car but then to remove the currently display car from the list so as to reduce the duplication.

On my view I am taking @cars and rendering this view for each of them:

<div class="car__photo">
  <div class="car__photo-inner">
    <%= image_tag car.s3_photo(:thumb), class: 'styled-picture' %>
  </div>
</div>

<div class="car__info">
  <h4 class="car__info__name"><%= car.name %></h4>
  <p class="car__info__park"><%= car.park_name %></p>
</div>

<%= link_to car.name + ' at ' + car.showroom_name, car_path(car), class: 'car__link' %>

My expected output is for @cars to be a list of all the cars in the same showroom as @car but without @car itself.

Was it helpful?

Solution

You get undefined method 'cars' for nil:NilClass error because cars.delete(self) is actually deleting the current car from database.

def other_cars_in_showroom
  cars = self.showroom.cars
  cars.delete(self) ## Fires delete query for self(deletes current car)
  cars
end

Update the show action as below, to get all the other cars in the showroom of the selected car except the selected car:

def show
  @car = Car.friendly.find(params[:id])
  @cars = @car.other_cars_in_showroom
end

Update the other_cars_in_showroom as below:

def other_cars_in_showroom
  showroom.cars.where.not(id: self.id)
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top