views:

276

answers:

1

Hello,

By any chance is it possible to create a conditional association with DataMapper?

For example:

I want the User have n Apps just if that user have the attribute :developer => true

something like this:

class User
  include DataMapper::Resource
  property :id, Serial
  property :name, String, :nullable => false
  property :screen_name, String, :nullable => false, :unique => true
  property :email, String, :nullable => false, :unique => true, :format => :email_address
  property :password, BCryptHash, :nullable => false
  property :developer, Boolean, :default => false

  #The user just gets apps if developer
  has n :apps #,:conditions => "developer = 't'"

end

class App
  include DataMapper::Resource
  property :id, Serial
  property :name, String, :nullable => false

  belongs_to :user
end

I know that this would be possible by creating a subclass from User as a Developer::User and in that class, use the has n, but I really would like to know if its possible to make it directly on the association declaration.

Another way I also managed to do when using ARn was to extend the association and rewriting the methods for each action.

So on the extension module I could have something like this:

module PreventDeveloperActions
  def new
    if proxy_owner.developer?
       super
    else
       raise NoMethodError, "Only Developers can create new applications"
    end
  end

 # and so on for all the actions ...
end

But again, I really would like to avoid the use of this solutions if possible, but just if it's possible to perform a quick and direct method easily with DataMapper :)

Thanks in advance

+2  A: 

At the moment, conditions that you include in the relationship declaration only apply to the target. So if the target model has an :active property, you can say things like has n, :apps, :active => true. Unfortunately you can't define relationships that are only active given the current state of the source (yet).

There are some proposals I'm considering to expand the Query logic in DM, but I'm unsure what the impact will be to the code, and what extra capabilities it will provide aside from this. It may be something we tackle after DM 1.0, since it also affects 50+ adapters and plugins.

STI is normally what I'd recommend for something like this, since it will allow you to define relationships that only exist for that type of object. Another approach would be to define the relationships as normal, mark the accessor/mutator methods as private, and then add a proxy method that does the equivalent of return apps if developer?.

dkubb
Hi Dan, thank you very much for you attention and support, Its really appreciated :) I will try these methods you've mentioned, but I'm pretty sure this will solve my problem :) thanks again
ludicco