开发者

How can I assign without using self.attribute = in rails?

开发者 https://www.devze.com 2023-03-12 09:25 出处:网络
SO, I have been working on this for a while, I posted a much larger question that didn\'t get any replies, but I\'ll ask a much simpler one here.

SO,

I have been working on this for a while, I posted a much larger question that didn't get any replies, but I'll ask a much simpler one here.

My question is, how else can I assign something without using self.attribute = in the following context:

 def photo_from_url(url)
   remote_photo = open(url)
   def remote_photo.original_filename;base_uri.path.split('/').last; end
   **self.photo = remote_photo**
   self.save
 end

I need to make photo_from_url a class method so I can call it from delayed_job however when I add self, it gives me "no method found photo=".

Please help开发者_运维问答! Thanks in advance...


Option 1: you want to create new object each time you call this method:

class Photo < ActiveRecord::Base
  def self.photo_from_url(url)
    ...

    new(:photo => remote_photo).save!
  end
end

Option 2: you want to update existing object, then you need to get object id you want to modify:

class Photo < ActiveRecord::Base
  def self.photo_from_url(url)
    ...

    id = # here you find id, e.g. from url 
    find(id).update_attributes!(:photo => remote_photo)
  end
end


A class method, by definition, does not reference any specific object instance. Therefore, you must have a way to get the object you want to modify. The simplest solution would be to pass a reference of that object into your class method and use that instead of self.

class Foo
  def self.photo_from_url(url, obj)
     ... 
     obj.photo = remote_photo
     ...
  end
end

Example usage:

foo = Foo.new # creates a new instance of Foo
Foo.photo_from_url("http://example.com/photo/12341", foo)

Notice how I am calling photo_from_url as a class method? That is because it is operating on the Foo class and not an instance of Foo, which happens to be foo here.


Here is some literature on the difference between class and instance methods:

Class and Instance Methods in Ruby

0

精彩评论

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