开发者

find_or_create method not work in Rails rake task

I have written rake task like as below,

namespace :db do
  desc "load photo"
  task :load_photo  => :environment do
    begin
      model=Model.find_or_create_by_photo(:name => open("http://domain.com/jsx.jpg"))
    end
      puts "complete"
    rescue Exception =&g开发者_StackOverflow中文版t; e
      puts e
    end
  end   
end

When I ran rake db:load_photo got an error " **undefined method 'find_or_create_by_photo'** for #<Class:0x37079e8>" Please help me to feature this out?

Thanks in advance.


The find_and_create_by methods are genereated dynamicly (as the find_by or the create_by methods). If you call Model.find_or_create_by_column Ruby raises a NoMethodError. The error is called within a rescue block. If this error occurs Rails is looking for columns in your model, that matches the method name. If a column is found, the method is created dynamicly. If no such method is found, the error is raised again.

Check if you really have a column named photo. Normally this should work.


If photo is an attribute:

Model.find_or_create_by_photo photo_name_string

If photo is an association:

Model.find_or_create_by_photo_id 7

For your paperclip case (with a DB column named 'photo_file_name'):

Model.find_or_create_by_photo_file_name 'lala.png'


Here is my Model code, I'm using paperclip as a gem, model attributes are photo_file_name, photo_content_type and photo_file_size.

        class Model < ActiveRecord::Base  
           has_attached_file :photo, :styles => { :small => "150x150>", :thumb => "75x75>" } 
        end 
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜