find_or_create method not work in Rails rake task - ruby-on-rails

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 => 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

Related

Paperclip Rails error when trying to refresh

My User model:
class User < ActiveRecord::Base
has_attached_file :avatar, :styles => { :profile => "200x200>", :collab => "300x200>", :msg => "50x50>" }, :default_url => "missing.png"
validates_attachment_content_type :avatar, :content_type => /\Aimage\/.*\Z/
...
I have just added the :msg and :profile styles and I'm trying to refresh them so they show up properly in my views.
I've tried running:
rake paperclip:refresh CLASS=User
and I get this error:
rake aborted!
ArgumentError: wrong number of arguments (0 for 1)
/home/jrile/rails/cs480/app/models/user.rb:44:in `hash'
/home/jrile/.rvm/gems/ruby-2.1.0/gems/paperclip-4.1.1/lib/paperclip/attachment_registry.rb:42:in `names_for'
/home/jrile/.rvm/gems/ruby-2.1.0/gems/paperclip-4.1.1/lib/paperclip/attachment_registry.rb:16:in `names_for'
/home/jrile/rails/cs480/lib/tasks/paperclip.rake:15:in `obtain_attachments'
Here's line 44 of user.rb (not sure why this has anything to do with paperclip)
def User.hash(token)
Digest::SHA1.hexdigest(token.to_s)
end
I was trying to add an avatar following railstutorial.org.
EDIT: Also, in all my views where I'm trying to display the avatar, it's displaying ":msg" even if I'm trying to display one of the other two. I.E.,
<%= image_tag user.avatar.url(:profile) %>
is showing the 50x50 avatar.
For the first issue, from this SO question
You shouldn't override ruby core methods like object#hash they are made for specific reasons and changing their behavior could cause unexpected results , apparently later on the tutorial this will change to:
def User.digest(token)
Digest::SHA1.hexdigest(token.to_s)
end

Rails model returning nil ID

I need to get the id of a certain object. It's probably something really simple that I am missing. The object I need comes out from the database, and I'm able to retrieve its attributes but not the id.
Part.where("code ='p8z68vprogen3'").first
# => <Part id: 486, code: "p8z68vprogen3", etc...>
Part.where("code ='p8z68vprogen3'").first.id
# => nil
Part.where("code ='p8z68vprogen3'").first.code
# => "p8z68vprogen3"
This is the model:
class Part < ActiveRecord::Base
has_many :build_parts
has_many :builds, :through => :build_parts
belongs_to :category
attr_accessible :code,:link,:description,:category_id
end
I suppose it's something related to attr_accessible or attr_accessor, I tried to fiddle with them but nothing so I ask for help.
EDIT:
asking for a reload returns an error in any way i try i get the object(where or find_by_)
part_needed = Part.where("code ='p8z68vprogen3'").first
# => <Part id: 486, code: "p8z68vprogen3", etc..>
part_needed.reload
# ActiveRecord::RecordNotFound: Couldn't find Part without an ID
Also, the parts table is already populated, but here is the code that creates an entry:
part = Part.new(
:description => objs[1],
:code => objs[2],
:category_id => tips[objs[3].to_i]
)
part.save!
This code is executed in another part of the code is not just before where I try to get the ID.
Restart your machine. I know it doesn't sound logical. I encountered a problem where I had two objects of the same class and the first/last method returned the last object. Restarting worked for me. (rails 3.1.1, ruby 1.9.2p320 (2012-04-20 revision 35421) [i686-linux])
)

Custom Paperclip processor not being called

I have a user model that is generated using Devise. I am extending this model using paperclip to enable file upload and also the processing of a file using a custom paperclip processor.
My paperclip field is declared in the user model as follows. PaperClipStorage is a hash that I create with the paperclip variables. Also, the being stored on AWS S3.
has_attached_file :rb_resume, PaperclipStorageHash.merge(:style => { :contents => 'resume_contents'}, :processors => [:resume_builder])
validates_attachment_content_type :rb_resume, :if => lambda { |x| x.rb_resume? }, :content_type => ['application/pdf', 'application/x-pdf', 'application/msword', 'application/x-doc']
The validates_attachment_content_type check is being done to make sure that it only processes pdf and MS word files.
My processor looks as follows
module Paperclip
class ResumeBuilder < Processor
def initialize(file,options = {}, attachment = nil)
#file = file
#attachment = attachment
puts "Attachment is not null " if !attachment.nil?
end
def make
rb = MyModule::MyClass.new(#file.path) ### Do something with the file
section_layout = rb.parse_html
#attachment.instance_write(:whiny, section_layout)
#file
end
end
end
In my user model I also have an after_save callback that is supposed to take the section_layout generated in the processors make method. Code is as follows
after_save :save_sections
def save_sections
section_layout = rb_resume.instance_read(:whiny)
# Do something with section_layout...
end
Now my problem is that the processor code is never being called, and I can't figure out why.
Because of that the section_layout variable is always nil.
Another point to note is that the same model also has two other has_attached_file attributes. None of the other two use a custom processor.
I've been struggling with this for last 3 hours. Any help would be greatly appreciate.
Thanks
Paul
Error in my has_attached_file declaration
has_attached_file :rb_resume, PaperclipStorageHash.merge(:style => { :contents => 'resume_contents'}, :processors => [:resume_builder])
should actually be
has_attached_file :rb_resume, PaperclipStorageHash.merge(:styles => { :contents => 'resume_contents'}, :processors => [:resume_builder])
Notice the plural styles as opposed to singular style

Rails 3: using composed_of with validation causes ActiveRecord error

I am using the following code snippet from the Rails docs to convert IPs into integers before inserting them into the database:
composed_of :user_ip,
:class_name => 'IPAddr',
:mapping => %w(user_ip to_i),
:constructor => Proc.new { |ip| IPAddr.new(ip, Socket::AF_INET) },
:converter => Proc.new { |ip| ip.is_a?(Integer) ? IPAddr.new(ip, Socket::AF_INET) : IPAddr.new(ip.to_s) }
The composed_of block is then followed by this simple validation:
validates_uniqueness_of :user_ip
But the validation in turn throws an error when trying to create a new object:
TypeError: Cannot visit IPAddr
Remove the validation and the error is gone.
If I understand correctly, this is happening because :user_ip becomes an IPAddr object, and that does not sit well with ActiveRecord. Is this correct, and if so, is there a way around it?
Not sure if you ever found a solution to this, but I was able to patch it in my gem by adding a visit method to Arel.
You should be able to do something like the following to get it to work. This is based on how Arel converts values for other types of objects such as dates. Not sure if you need to convert the value to a string, but it might just work as an integer.
module Arel
module Visitors
class ToSql
def visit_IPAddr
quote(value.to_i)
end
end
end
end
I needed to be able to dynamically generate these methods so I used the following in my gem:
Arel::Visitors::ToSql.class_eval do
define_method "visit_#{klass.name}", lambda {|value| quote(value.to_s) }
end

Rails as_json include parent object?

Hello I'm trying to use as_json to output the parent object as an include.
Here is my code :
photo.as_json(:include => [:comments, :likes])
This code works, this one doesn't :
photo.as_json(:include => [:comments, :likes, :user])
I get the error :
NoMethodError: undefined method `macro' for nil:NilClass
Any one ?
Thanks :)
Try
user = User.find(1)
user.as_json(:include => {:photos => {:include => [:comments, :likes]}})
I ended up using acts_as_api which allows for methods, templates and a lot of cool features that got the work done much easier.
you call the "methods" option instead:
photo.as_json(:methods => [:user], :include => [:comments, :likes, :user])
I've used this in Rails 4.0, ruby 2.0 to bring back what i need.

Resources