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 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 (IE 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
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
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.