我有2个型号:
class User < ActiveRecord::Base
has_and_belongs_to_many :groups
end
class Group < ActiveRecord::Base
has_and_belongs_to_many :users
end
Run Code Online (Sandbox Code Playgroud)
我想创建一个范围(这对于效率和链接范围的能力很重要),它返回不属于任何组的用户.多次尝试后,我在做的方法,而不是范围,这使得失败collect的User.all是丑陋和..不正确的.
有帮助吗?
也许对于第二个问题:我设法创建一个范围,返回属于任何给定组的用户(作为id的数组给出).
scope :in_groups, lambda { |g|
{
:joins => :groups,
:conditions => {:groups => {:id => g}},
:select => "DISTINCT `users`.*" # kill duplicates
}
}
Run Code Online (Sandbox Code Playgroud)
可以更好/更漂亮吗?(使用Rails 3.0.9)
activerecord ruby-on-rails associations has-and-belongs-to-many
我想上传pdf文件,并创建(作为单独的文件)缩略图图像,其中PDF的前3页水平对齐.我设法用RMagick做一个Paperclip处理器来生成该文件,但问题是:我希望单独的文件(带有缩略图样式的文件)具有正确的扩展名(例如jpg)而不是原始的pdf.如果我仍然可以通过使用带样式的url方法获得正确的路径,那将是很好的,例如:
>> attachment.url
=> "/some/path/id/original/test.pdf" # original file
>> attachment.url(:pdf_thumbnail)
=> "/some/path/id/pdf_thumbnail/test.jpg" # jpg file, not pdf
Run Code Online (Sandbox Code Playgroud)
一些代码:
module Paperclip
class PdfThumbnail < Processor
def initialize(file, options = {}, attachment = nil)
super
@file = file
@instance = options[:instance]
@current_format = File.extname(@file.path)
@basename = File.basename(@file.path, @current_format)
end
def make
dst = Tempfile.new([@basename, 'jpg'].compact.join("."))
dst.binmode
pdf = ::Magick::ImageList.new(File.expand_path(@file.path))
image = pdf[0..2].append(false)
image.format = 'JPG'
image.write(File.expand_path(dst.path))
dst.flush
return dst
end
end
end
Run Code Online (Sandbox Code Playgroud)
has_attached_file :file, :styles => {:pdf_thumbnail => ""}, :processors …Run Code Online (Sandbox Code Playgroud)