Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/22.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby 如何按类别名称筛选所有广告?_Ruby_Ruby On Rails 3_Activerecord_Where - Fatal编程技术网

Ruby 如何按类别名称筛选所有广告?

Ruby 如何按类别名称筛选所有广告?,ruby,ruby-on-rails-3,activerecord,where,Ruby,Ruby On Rails 3,Activerecord,Where,我的用例很简单: 获取类别名称为params[:category_name]的所有广告 以下是我的模型关联: class Ad < ActiveRecord::Base belongs_to :category attr_accessible :anonymous, :celular, :name, :precio, :category_id end class Category < ActiveRecord::Base has_many :ads attr_

我的用例很简单:

获取类别名称为params[:category_name]的所有广告


以下是我的模型关联:

class Ad < ActiveRecord::Base
  belongs_to :category

  attr_accessible :anonymous, :celular, :name, :precio, :category_id
end

class Category < ActiveRecord::Base
  has_many :ads

  attr_accessible :name
end
但它没有按预期工作,我有一个例外:

SQLite3::SQLException:没有这样的列:ads.category:从“ads”中选择“ads”。*其中的“ads”。“category”=“aeronautica”

如何按类别名称筛选广告对象

Ad.where(:category => Category.find_by_name(params[:category_name]))
params[:category\u name]
只是一个字符串,而
:category
是category类型的对象

Category.find_by_name
将为您提供一个类别对象,您可以将其与
:Category

编辑:

对于这种特殊情况,您可以尝试以下方法,因为您可能使用了
category\u id:integer
而不是
category:reference
来创建广告模型

Ad.where(:category_id => Category.find_by_name(params[:category_name]).id)
params[:category\u name]
只是一个字符串,而
:category
是category类型的对象

Category.find_by_name
将为您提供一个类别对象,您可以将其与
:Category

编辑:

对于这种特殊情况,您可以尝试以下方法,因为您可能使用了
category\u id:integer
而不是
category:reference
来创建广告模型

Ad.where(:category_id => Category.find_by_name(params[:category_name]).id)

在ads数据库中,您只有一个名为category_id的列,因此在ads数据库中搜索类别名称没有任何用处

 Category.find_by_name(params[:category_name]).ads

这将使用参数中的category_名称显示类别的所有广告。

在ads数据库中,您只有一个名为category_id的列,因此在ads数据库中搜索类别名称没有任何用处

 Category.find_by_name(params[:category_name]).ads

这将显示带有参数中类别名称的类别的所有广告。

前面缺少括号。adsOops,我真的应该多加注意。;)之前缺少括号。adsOops,我真的应该多加注意。;)
SQLite3::SQLException:没有这样的列:ads.category:从“ads”中选择“ads”。*其中“category”为空
-有什么想法吗?创建ads表时,是否添加了对category的引用?比如,
rails g model ad anonymous:integer celular:integer name:string precio:string*category:reference*
您是否使用了
category:reference
category\u id:integer
SQLite3::SQLException:no这样的列:ads.category:从“ads”中选择“ads”。*是否为空
-有什么想法吗?创建Ads表时,是否添加了对类别的引用?比如,
rails g model ad anonymous:integer celular:integer name:string precio:string*category:reference*
您使用了
category:reference
还是
category\u id:integer