I have a User
model which has many roles
. Roles contains a user_id
field, which I want to validate_presence_of
The is
After researching a bit, this solution seems to be easiest. First, in your Role
model, instead of validating user_id
, validate user
:
validates :user, :presence => true
Then, in your User
model, add :inverse_of => :user
to your has_many
call:
has_many :roles, :inverse_of => :user
Then it works as expected:
irb(main):001:0> @user = User.new
=> #
irb(main):002:0> @user.roles << Role.new(:name => "blah")
=> [#]
irb(main):003:0> @user.roles[0].user
=> #
irb(main):004:0> @user.save
(0.1ms) begin transaction
SQL (3.3ms) INSERT INTO "users" ("created_at", "updated_at") VALUES (?, ?) [["created_at", Fri, 04 Jan 2013 02:29:33 UTC +00:00], ["updated_at", Fri, 04 Jan 2013 02:29:33 UTC +00:00]]
User Load (0.1ms) SELECT "users".* FROM "users" WHERE "users"."id" = 3 LIMIT 1
SQL (0.2ms) INSERT INTO "roles" ("created_at", "name", "updated_at", "user_id") VALUES (?, ?, ?, ?) [["created_at", Fri, 04 Jan 2013 02:29:34 UTC +00:00], ["name", "blah"], ["updated_at", Fri, 04 Jan 2013 02:29:34 UTC +00:00], ["user_id", 3]]
(1.9ms) commit transaction
=> true
irb(main):005:0> @user.roles.first
=> #
Note, however, that this still produces two SQL transactions, one to save the user and one to save the role. I don't see how you can avoid that.
See also: How can you validate the presence of a belongs to association with Rails?