Rails 3 Attribute Validation
I didn't do much with these JQuery-tokeninput or Rails virtual attributes, but I hit my head against the wall. Any help or guidance is appreciated.
I have a virtual attributes reader in my ad model where I need to check for existence:
attr_reader :classroom_tokens
validates :classroom_tokens, :presence => true``
followed by a getter and setter:
def classroom_tokens=(ids)
self.classroom_tokens = ids.split(",")
end
def classroom_tokens
#Tried several things here
end
I just need to make sure the [: announcement] [: classroom_tokens] parameters are not empty. The called validator seems to be looking at something else as it is always empty no matter what. What am I missing? Any help is 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|
source to share
Instead of setting, self.classroom_tokens
just set an instance variable @classroom_tokens
and then remove the method classroom_tokens
as you are implicitly defining it with attr_reader
. The code should look like this:
attr_reader :classroom_tokens
validates :classroom_tokens, :presence => true``
def classroom_tokens=(ids)
@classroom_tokens = ids.split(",")
end
source to share