Search code examples
ruby-on-railsvirtual-attributejquery-tokeninput

Virtual attribute validation Rails 3


I have not done a whole lot with this Jquery-tokeninput or Rails virtual attributes but have been slamming my head against the wall with this one. Any help or guidance is appreciated.

I have a virtual attribute reader in my announcement model which I need to validate presence of:

attr_reader :classroom_tokens
validates :classroom_tokens, :presence => true``

followed by the getter and setter:

def classroom_tokens=(ids)
    self.classroom_tokens = ids.split(",")
end

def classroom_tokens
    #Tried several things here
end 

I really just need to make sure params[:announcement][:classroom_tokens] is not empty. The validate call above seems to be looking at something else since it things it is always empty no matter what. What am I missing? Any help is greatly appreciated.

Rails 3.1 Ruby 1.9.2

UPDATE: If I do

#Announcement MODEL
attr_reader :classroom_tokens
#validates :classroom_tokens, :presence => true
def classroom_tokens=(ids)
  @classroom_tokens = ids.split(",")
end

#Announcement_controller create action
puts "Token=>#{@announcement.classroom_tokens}|"
puts "Params=>#{params[:announcement][:classroom_tokens]}|" 

I get:

Token=>|
Params=>7,13,12|

Solution

  • Instead of setting self.classroom_tokens, just set the instance variable @classroom_tokens, and then remove the classroom_tokens method, since you're implicitly defining it by using attr_reader. The code should look like:

    attr_reader :classroom_tokens
    validates :classroom_tokens, :presence => true``
    
    def classroom_tokens=(ids)
        @classroom_tokens = ids.split(",")
    end