G5 / storext

Add type-casting and other features on top of ActiveRecord::Store.store_accessor
MIT License
210 stars 55 forks source link

How do I manage validatations of attributes with Storext? #67

Closed catharinavas closed 4 years ago

catharinavas commented 4 years ago

I would like to do something like this: image But I get this error on group.save! :

PG::UndefinedColumn: ERROR:  column groups.name does not exist
LINE 1: SELECT 1 AS one FROM "groups" WHERE "groups"."name" = $1 LIM...

How can I make it work?

Thank you for the help. I'm still trying to figure out how to work with JSONB columns...

ramontayag commented 4 years ago

Yes, I didn't expect that to work because the built-in Rails validations were made for normal columns. If all your records have the use for name, I suggest making it a normal column. If you're sure you want name to be a jsonb column, you will need to make your own validation:

def validate_name_uniqueness
  arel = where("preferences ->> 'name' = '#{name}'")
  arel = arel.where.not(id: id) if self.persisted?
  return true if arel.empty?
  errors.add(:name, "must be unique")
end

This gist has many query examples.

catharinavas commented 4 years ago

I will take a look there. Thank you!