Search code examples
sqlruby-on-railsassociationsmodel-associations

Does rails association prevents a new record to be created like a foreign_key on a SQL create table would?


I know this is a very simple question but I couldn't really find any clarification anywhere I look.

So if I have:

class Task < ActiveRecord::Base
    belongs_to :group
end

and

class Group < ActiveRecord::Base
    has_many :tasks
end

Does this prevents the creation of a new task record if the group_id given while creating task does not exist in group?

Because I've tried this and it's not preventing me from doing so unlike an actual foreign_key attribute on a SQL table (which rails does not add to its table)


Solution

  • No - it doesn't automatically do any validation in rails, and it doesn't add any database validations either.

    If you wanted you could validate it yourself:

    class Task < ActiveRecord::Base
      belongs_to :group
      validate :group_exists?
    
      def group_exists?
        !!self.group_id && Group.exists?(:id => self.group_id)
      end
    end
    

    There are gems which can help with this, and you can also use validates_presence_of :group. See this SO question for more discussion: validates_presence_of with belongs_to associations, the right way