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

StackOverflow https://stackoverflow.com/questions/23536068

سؤال

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)

هل كانت مفيدة؟

المحلول

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

نصائح أخرى

No it won't - there's a difference between setting foreign_keys and assigning objects

In ActiveRecord, as far as I know, you have to pass an integer to the foreign_key field. You can set the integer to be anything you want, allowing you to set invalid ones if you wish

If you pass a ruby object (I.E saving group: @group), you're basically going to have to pass a valid object for Rails to save it

That's as much as I know

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top