开发者

Rails3, one-to-many relationship, how to check if child model's parent_id is valid when save

开发者 https://www.devze.com 2023-01-26 16:54 出处:网络
I have two models which are Parent and Child. Parent has many children and Child has one parent. one-to-many relationship using has_many and belongs_to. Child has parent_id field, of course.

I have two models which are Parent and Child. Parent has many children and Child has one parent. one-to-many relationship using has_many and belongs_to. Child has parent_id field, of course.

I'd like to check valid开发者_运维百科ation for Child if its parent_id is valid(means such Parent has the ID exists).

I thought validates_associated is for that, but didn't work in unittest.

Do I have to create own validator or are there more general methods?


Why don't you add a database foreign key constraint in your migration? Something like

    class CreatePages < ActiveRecord::Migration
      def self.up
        create_table :pages do |t|
          t.references :upload, :null => false
          t.integer :number
          t.integer :position
          t.integer :color

          t.timestamps
        end

        execute "ALTER TABLE pages 
                 ADD CONSTRAINT fk_pages_upload_id
                 FOREIGN KEY (upload_id) REFERENCES uploads(id)"
      end

      def self.down
        execute "ALTER TABLE pages DROP CONSTRAINT fk_pages_upload_id"
        drop_table :pages
      end
end

This may not look like a "Rails" way of doing things, but personnaly, I have the feeling databases are underused in web applications. Constraints are powerful, why not use them!

Best regards,

Philippe


You'll need to use both validates_associated and validates_presence_of on the child model to ensure that both the foriegn_key is populated, and the the parent model exists in that table. See the note on the docs here validates_associated

0

精彩评论

暂无评论...
验证码 换一张
取 消