Ruby on Rails Wednesday, November 2, 2011

Looking for some guidance/support on what feels like might not be an
uncommon use-case.

`User.has_many accounts`
`User.has_many payment_methods`
`Account.belongs_to :user`
`Account.belongs_to :payment_method`
`PaymentMethod.has_many :accounts`

There are lots of `Accounts`. When I (a `User`) want to assign
accounts to a `PaymentMethod`, I really don't want to scope against
all of them, but rather only those that I own. While this can be done
at the controller level, it feels like a data-level constraint.

I will want a validation, to ensure I do not map `PaymentMethods` to
`Accounts` with different `Users`. But I will also want a way to
specify the scope of possible associations, effectively using the same
logic as the validation. Placing conditions on the association doesn't
restrict invalid associations, nor does it imply that.

A useful syntax might be:

`PaymentMethod.has_many :accounts, requirement: proc {self.user ==
target.user}, scope: true, validate: true`

Expressing `my_payment_method.accounts` would use `requirement` as a
condition. A reflection on the association
(`PaymentMethod.possible_accounts`) could return a relation that could
be used to scope out the possible valid associations from the target
(`Accounts`). The validate flag could generate a matching DRY
validation that ensures the same condition at the instance level.

Realizing that crossing realms of associations and validations might
not be the most desirable, but seem inherently required in order to
avoid repetition.

Does anyone have any insight on this?

--
You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group.
To post to this group, send email to rubyonrails-talk@googlegroups.com.
To unsubscribe from this group, send email to rubyonrails-talk+unsubscribe@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.

No comments:

Post a Comment