Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ruby-on-rails-3/4.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 on rails 3 如何通过虚拟属性获取ActiveRecord记录?_Ruby On Rails 3_Activerecord_Virtual Attribute - Fatal编程技术网

Ruby on rails 3 如何通过虚拟属性获取ActiveRecord记录?

Ruby on rails 3 如何通过虚拟属性获取ActiveRecord记录?,ruby-on-rails-3,activerecord,virtual-attribute,Ruby On Rails 3,Activerecord,Virtual Attribute,在Rails3中,如何通过查找虚拟属性来检索记录?我有一个name列和一个slug对其进行简单修改(参见下面的代码)。如何通过slug到name进行“反向查找” 我正在尝试为下面的find_by_slug方法找到正确的代码: class Brand < ActiveRecord::Base has_many :sale_items validates :name, :uniqueness => true def slug self.name.downcase.g

在Rails3中,如何通过查找虚拟属性来检索记录?我有一个
name
列和一个
slug
对其进行简单修改(参见下面的代码)。如何通过
slug
name
进行“反向查找”

我正在尝试为下面的
find_by_slug
方法找到正确的代码:

class Brand < ActiveRecord::Base
  has_many :sale_items
  validates :name, :uniqueness => true

  def slug
    self.name.downcase.gsub(/\s/, '-')
  end

  def self.find_by_slug(given_slug)
    first(slug: given_slug)
  end
end
class品牌true
def段塞
self.name.downcase.gsub(/\s/,'-'))
结束
def self.find_by_slug(给定_slug)
第一(段塞:给定的_段塞)
结束
结束
当我在Rails控制台中尝试
find_by_slug
时,我收到一个
未知键:slug
错误


这个问题看起来很相似,但我不确定是否和我的问题一样。我希望能得到一些启发和帮助

因为slug在数据库中不存在,所以不能先用slug查询。你需要做的是搜索名字。但为了做到这一点,您的“名称到段塞”映射需要是可逆的。你需要能够做到

name = 'San Francisco'
slug = convert_to_slug(name)  #san-francisco
name == convert_to_name(slug) #true
所以,给定一个蛞蝓,你知道它的名字是什么-然后你就可以找到它的名字了。现在你的子弹转换

downcase.gsub(/\s/, '-')
是不可逆的,除非有一些你没有和我们分享的隐含信息,比如“只有空格,每个首字母都大写”。所以这是不可能的,你最好让它成为一个常规属性,而不是一个虚拟属性。如果你的转换是可逆的,那么你只需要使用

find_by_name(convert_to_name(slug))

你说得对,这是不可逆的,因为有些名字有连字符,而有些名字在单词之间有空格。我会接受你的建议,让它成为常规属性。