Ruby on rails 如何使用子记录参数检索父记录
我有一个办公室和位置模型。和你有一种关系 我试图有一个搜索功能,用户可以根据邮政编码查看所有的办公室 在办公室控制器中,我放置了如下内容:Ruby on rails 如何使用子记录参数检索父记录,ruby-on-rails,ruby-on-rails-4,activerecord,active-record-query,Ruby On Rails,Ruby On Rails 4,Activerecord,Active Record Query,我有一个办公室和位置模型。和你有一种关系 我试图有一个搜索功能,用户可以根据邮政编码查看所有的办公室 在办公室控制器中,我放置了如下内容: def index if params[:search] @offices = Office.find_each do |office| return office if office.location.zip == params[:search] end else @offices
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
但当我提交zip值时,视图中出现了一个零错误
office.rb
class Office < ActiveRecord::Base
has_one :location
end
location.rb
class Location < ActiveRecord::Base
belongs_to :office
end
我不认为find_每个块中的return语句是在做你想要做的事情 尝试将控制器代码更改为:
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