Domanda

I'm attempting to understand the difference between these two ways of assigning virtual attributes in Rails 4. One of them causes a "stack level too deep" and one of them works fine. I'm attempting to use the new ActiveRecord array field by parsing a textfield and splitting it by commas to create a tag field. The working code is as follows:

class Post < ActiveRecord::Base
  def tags=(s)
    self[:tags] = s.split(/,\s+/)
  end
end

However, when I change this to assign the tag field in this model by assigning to the class variable, it causes a "stack level too deep".

class Post < ActiveRecord::Base
  def tags=(s)
    self.tags = s.split(/,\s+/)
  end
end

Can someone explain why this happens to me? It seems like using self.tags causes this virtual attribute to be run until the stack blows up. Which part of ActiveRecord causes this?

È stato utile?

Soluzione

The stack level too deep error has nothing to do with rails. Any basic Ruby class would do this:

class Post
  def tags=(s)
    self.tags = s
  end
end

> Post.new.tags = "a,b,c"
SystemStackError: stack level too deep     

Calling self.tags = will just re-execute tags=(s) on the same object, over and over again. In your first example, you're directly setting the attribute via self[:tags] =, which doesn't re-execute tags=(s) at all. I would assume an oversimplification of ActiveRecord is that it does something like your first example for all of a model's fields.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top