tomekfranek
tomekfranek

Reputation: 7099

How should I refactor create_unique methods in Rails 3?

I have following ugly create_unique method in few models ex:

  def self.create_unique(p)
    s = Subscription.find :first, :conditions => ['user_id = ? AND app_id = ?', p[:user_id], p[:app_id]]
    Subscription.create(p) if !s
  end

And then in controllers #create actions I have

s = Subscription.create_unique({:user_id => current_user.id, :app_id => app.id})
if s
  raise Exceptions::NotAuthorized unless current_user == s.user
  @app = s.app
  s.destroy
  flash[:notice] = 'You have been unsubscribed from '[email protected]+'.'
  redirect_to '/'
end

Upvotes: 1

Views: 74

Answers (2)

Amar
Amar

Reputation: 6942

You can use validates_uniquness_of :app_id,:scope=>:user_id so app id is uniq for respected user_id

Upvotes: 0

Fivell
Fivell

Reputation: 11929

did you try dynamic finders ?

find_or_initialize_by_user_id_and_app_id
find_or_create_by_user_id_and_app_id
first_or_initialize...
first_or_create....

check manual http://guides.rubyonrails.org/active_record_querying.html#dynamic-finders

also option is to create validation rule for check unique value

class Subscription < ActiveRecord::Base
   validates_uniqueness_of :user_id, :scope => :app_id
end

then

sub = Subscription.new({:user_id => current_user.id, :app_id => app.id})
sub.valid? #false 

Upvotes: 1

Related Questions