Forum: Ruby on Rails How to refactor complicated logic in create_unique method?

Posted by Darek F. (darek_f)
on 2012-10-08 20:40
(Received via mailing list)
I would like to simplify this complicated logic for creating unique 
Track
object.

def self.create_unique(p)
  f = Track.find :first, :conditions => ['user_id = ? AND target_id = ? 
AND target_type = ?', p[:user_id], p[:target_id], p[:target_type]]
  x = ((p[:target_type] == 'User') and (p[:user_id] == p[:target_id]))
  Track.create(p) if (!f and !x)
end
Posted by Colin Law (Guest)
on 2012-10-08 21:29
(Received via mailing list)
On 7 October 2012 01:43, Darek Finster <dariusz.finster@gmail.com> 
wrote:
> I would like to simplify this complicated logic for creating unique Track
> object.
>
> def self.create_unique(p)
>   f = Track.find :first, :conditions => ['user_id = ? AND target_id = ? AND
> target_type = ?', p[:user_id], p[:target_id], p[:target_type]]
>   x = ((p[:target_type] == 'User') and (p[:user_id] == p[:target_id]))
>   Track.create(p) if (!f and !x)
> end

For a start I would do the x=... first since it does not depend on f.
Then you only need to do the find if x true.  Then in the find use
.count and test it for >0 rather then finding a record.  Also extract
the find out into one or more scopes.
Are there relationships between user and track?  If so then you may be
able to use current_user.tracks rather than testing user_id.

Colin
Please log in before posting. Registration is free and takes only a minute.
Existing account (Switch to SSL-encrypted connection)
NEW: Do you have a Google/GoogleMail or Yahoo account? No registration required!
Log in with Google account | Log in with Yahoo account
No account? Register here.