开发者

Rails 3: Accessing parent object from inside a polymorphic rails model?

I have a polymorphic association - "address" (belongs to "addressable").

Amongst others, it s开发者_JS百科erves the "shop" model.

I'm trying to add a validates_presence_of validation when - and only when - the address has addressable_type "shop", and the corresponding "shop" object has "shop_type = 'commercial'

The problem is, I can't seem to access my parent "shop" object from the address model, which means I can't receive shop_type & consequently can't set the validation. Any suggestions on how to do this?

Here's an example of what I (think) I want to be doing. I'm not sure if this is the correct solution, but I suspect all I need is to figure out the "GET_SHOP_TYPE_HERE" call...assuming that's possible. Cheers

# app/models/address.rb

with_options :if => lambda { |address| address.addressable_type == 'Shop')} do |model|
  model.validates_presence_of :street_address, :suburb, :post_code, :address_state, :latitude, :longitude unless is_commercial_shop?
end

def is_commercial_shop?
  <GET_SHOP_TYPE_HERE> == 'commercial'
end


I might have misunderstock what you need, but I would try to do :

validate_presence_of :your_attribute, :if => has_condition?

def has_condition?
  # whatever code that tells you to validate or not
end

Hope this helps!

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜