ruby on rails - Preventing / Validating the creation of child relationships before commit in Rails3 -


i'm trying prevent users creating relationship in 'has many through' association record doesn't belong them.

my users have many locations through location_users. , locations have many shops through location_shops. have things protected cancan.

class user < activerecord::base   has_many :locationusers   has_many :locations, :through => :locationusers   end  class location < activerecord::base   has_many :locationusers   has_many :users, :through => :locationusers   has_many :location_shops   has_many :shops, :through => :location_shops end  class shop < activerecord::base   has_many :location_shops   has_many :locations, :through => :location_shops end 

and cancan abilities

class ability   can [:manage], shop, { :locationusers => {:user_id => user.id }}   can [:manage], location, { :locationusers => {:user_id => user.id }} end 

i can handle creation / editing of locations via setup , users can view / edit own locations / shops.

the issue creation of these relationships.

if user posts location id doesn't belong them, relationship created regardless of whether have permission create it. granted, can't view relationship need prevent creation in first place.

eg, user single location id 314

>> user.last.locations.map(&:id) => [314] 

when creating new shop, if alter params posted:

:shop=>{:shop_name=>"ye old shoppe", :location_ids => [1,2,3,314]}} 

the above creates relationship 4 locations obviously. need validate location ids before creation of relationship.

the thing come adding before_add in model:

class location   has_many :location_shops   has_many :shops, :through => :location_shops, :before_add => :check_location_ownership end 

is correct way go , if so, should :check_location_ownership like? or, there better way prevent creation of relationship?

although have done make sense, there 2 other ways can think of.

1) use :conditions option on has_many relationship.

2) custom validation method.

class location   has_many :location_shops   has_many :shops, :through => :location_shops   validate :check_location_ownership end 

i choose 1 of these 3 depending on case.


Comments

Popular posts from this blog

php - Wordpress website dashboard page or post editor content is not showing but front end data is showing properly -

javascript - Get parameter of GET request -

javascript - Twitter Bootstrap - how to add some more margin between tooltip popup and element -