how to retrieve parent record using child record params

43 views Asked by At

I have an office & location model. with has_one relation

Im trying to have a search feature, where user tries to see all offices based on zip code

In the office controllr I am placing something like this:

 def index
    if params[:search]  
      @offices = Office.find_each do |office|
        return office if office.location.zip == params[:search]
      end
    else
      @offices = Office.all
    end

  end

but I am getting a nil Error in the view when I submit a zip value.

office.rb

class Office < ActiveRecord::Base
  has_one :location
end

location.rb

class Location < ActiveRecord::Base
  belongs_to :office
end
1

There are 1 answers

0
nickwtf On

I don't think the return statement inside your find_each block is doing what you intend.

Try changing your controller code to:

def index
  if params[:search]  
    @offices = []
    Office.find_each do |office|
      @offices << office if office.location.zip == params[:search]
    end
  else
    @offices = Office.all
  end
end