我的ActiveRecord模型中有以下查询方法:
def self.tagged_with( string )
array = string.split(',').map{ |s| s.lstrip }
select('distinct photos.*').joins(:tags).where('tags.name' => array )
end
Run Code Online (Sandbox Code Playgroud)
因此,这将查找所有记录,这些记录具有从逗号分隔列表中获取的标记并转换为数组.
目前,这会将记录与任何匹配的标记匹配 - 如何使其在匹配所有标记的位置工作.
IE:如果我现在输入:"blue,red",那么我将获得所有用蓝色或红色标记的记录.
我想匹配所有用蓝色和红色标记的记录.
建议?
- 编辑 -
我的模型是这样的:
class Photo < ActiveRecord::Base
...
has_many :taggings, :dependent => :destroy
has_many :tags, :through => :taggings
...
def self.tagged_with( string )
array = string.split(',').map{ |s| s.lstrip }
select('distinct photos.*').joins(:tags).where('tags.name' => array )
end
...
end
class Tag < ActiveRecord::Base
has_many :taggings, :dependent => :destroy
has_many :photos, :through => :taggings
end
class Tagging < …
Run Code Online (Sandbox Code Playgroud) 我想知道是否可以做以下事情:
假设我有一个Foo
带有数据库属性的Rails模型value
.Foo
belongs_to Bar
,Bar
has_many Foos
.
在我的模型中,我想做的事情如下:
class Foo < ActiveRecord::Base
belongs_to :bar
def self.average
# return the value of all foos here
end
end
Run Code Online (Sandbox Code Playgroud)
理想情况下,我希望让这个方法返回一个与调用它的范围相匹配的值,这样:
Foo.average # would return the average value of all foos
@bar = Bar.find(1)
@bar.foos.average # would return the average of all foos where bar_id == 1
Run Code Online (Sandbox Code Playgroud)
可以做这样的事情,如果是这样,怎么办?谢谢!
我在表单助手中遇到了一个奇怪的错误.
我的模型看起来像这样:
class Folder < ActiveRecord::Base
...
# VIRTUAL ATTRIBUTES
def parent_name
self.parent.name
end
def parent_name=(name)
self.parent = self.class.find_by_name(name)
end
...
end
Run Code Online (Sandbox Code Playgroud)
我正在使用HAML和SimpleForm.当我像这样使用我的表格时......
= simple_form_for [@collection, form], :html => { :class => 'full' } do |f|
= f.input :name
= f.input :description
= f.submit
Run Code Online (Sandbox Code Playgroud)
......它完美无缺.但是如果我尝试像这样访问虚拟属性......
= simple_form_for [@collection, form], :html => { :class => 'full' } do |f|
= f.input :name
= f.input :parent_name
= f.input :description
= f.submit
Run Code Online (Sandbox Code Playgroud)
...我收到此错误:
NoMethodError in Folders#index
Showing ... where line #3 raised:
undefined …
Run Code Online (Sandbox Code Playgroud) 使用Rails 3.2,我正在研究API支持的模型(不是ActiveRecord).我希望能够to_json
在Rails控制器中调用此模型.在阅读了一堆ActiveModel文档后,我仍然不清楚一件事:
鉴于这样的模型:
class MyModel
attr_accessor :id, :name
def initialize(data)
@id = data[:id]
@name = data[:name]
end
def as_json
{id: @id, name: @name}
end
end
Run Code Online (Sandbox Code Playgroud)
这应该按预期工作,还是我还需要包含ActiveModel::Serializers::JSON
?我很难搞清楚as_json
/ to_json
方法通常定义的位置以及Rails何时在不同情况下自动调用哪些方法...
感谢您的任何见解!