0

我知道 rails 方法 find_by_name 但是如果我有一个对象而不是名称怎么办?假设我有@car@brand对象。我如何搜索所有cars具有特定对象的brand对象。

就像是@cars = Car.find_by_brand(@brand)

我试过@cars = @brand.cars了,但这似乎只拉了一个父模型。

编辑 - 有关代码的更多信息

汽车控制器:

has_and_belongs_to_many :brands

品牌型号:

  attr_accessible :name
  has_and_belongs_to_many :cars

品牌控制器

def create
@car = Car.find(params[:car_id])
@brand = Brand.create
@brand.assign_attributes({ :name => params[:brand][:brands][:name] })
@brand.cars << @car
if @brand.save
  redirect_to @car
else
  flash[:notice] = "Error!"
  redirect_to @car
end
end

def findcars
    @brand = Brand.find_by_name(params[:brand_name])
    @cars = @brand.cars
end

看法

<%= link_to brand.name, findcars_car_brand_path(@car, brand_name: brand.name), method: "get" %>

路线

resources :cars do    
    resources :brands do
        member { get :findcars }
    end
end

- 连接表没有模型

brands (name:string)

cars (name:string)

brands_cars (brand_id:integer, car_id:integer)

4

1 回答 1

1

我们先来看看 findcars。.joins(:brands)是关键,因为它允许您在构建 Car 对象时通过品牌条件( 'brands.attribute' => brand_value )缩小查询范围。

SQL 将如下所示:

SELECT "cars".* FROM "cars" INNER JOIN "cars_brands" ON "cars_brands"."car_id" = "cars"."id" INNER JOIN "brands" ON "brands"."id" = "cars_brands"."brand_id" WHERE "brands"."id" = 1

和这样的实现:

# If all you care about is the @cars - as the method name indicates
def findcars
    @cars = Car.joins(:brands).where('brands.name' => params[:brand_name])
end
# If you need both variables
def findcars
    @brand = Brand.find_by_name(params[:brand_name])
    @cars = Car.joins(:brands).where('brands.id' => @brand)
end

没有连接,你的 sql 看起来像这样:

SELECT "cars".* FROM "cars" WHERE "brands"."id" = 1

这将打破,因为“品牌”在这种情况下毫无意义。您需要为 rails 提供更多详细信息,以便它可以正确构建查询。

现在创建方法:

# @brand = Brand.create
# @brand.assign_attributes({ :name => params[:brand][:brands][:name] })
# params[:brand][:brands][:name] indicates something fishy with your form
# since this form is in the context of Brand, params[:name] should suffice 
@brand = Brand.create(:name => params[:brand][:brands][:name])

redirect_to @car是否意味着该表单是以汽车为中心的表单?在正确的上下文中使用 *form_for* 将简化对象的创建。

有关 2 个精彩的概述,请查看:

  1. http://guides.rubyonrails.org/active_record_querying.html
  2. http://guides.rubyonrails.org/association_basics.html
于 2013-02-20T20:05:34.613 回答