My Tag
model has some validations for attribute name
. It's wroking fine in all other cases. But when I call find_or_create_by_name
by this way:
# The last value of this string (by coma) is empty.
# So this record should not be saved.
tags_line = 'ruby, javascript, '
tags_line.split(',').each do |tag_name|
tag = Tag.find_or_create_by_name(tag_name.strip) do |new_tag|
new_tag.update_attribute :user_id, member.user.id
end
# Just append tag to this model
# through `has_and_belongs_to_many :tags`
tags << tag if tag
end
But this empty tag is even being saved. So, can be something wrong in this code?
NOTE: When I remove the block, it works:
...
tags_line.split(',').each do |tag_name|
# This way, invalid tag will not be created.
tag = Tag.find_or_create_by_name(tag_name.strip)
tags << tag if tag
end