Showing posts with label rails. Show all posts
Showing posts with label rails. Show all posts

Tuesday, July 8, 2014

Rails try method name in object

In rails, most cases we are using the following style of code to display name, text etc..
user && user.name
It will go lengthier & is hard to maintain, check the below one
user && !user.comments.blank? && user.comments.first.text
Avoid lengthy expressions, start using "try"
user.try(:name)
It will return user name only if user object exists. Happy coding..

Friday, October 30, 2009

has many polymorphic - double sided

I have used the following model relation to get the has many polymorphic double sided relation.

class Album < ActiveRecord::Base
has_many :album_files, :dependent => :destroy, :foreign_key => "album_id", :class_name => "AlbumFile"
has_many :photos, :source => :file, :through => :album_files, :source_type => "Photo", :class_name => "Photo"
has_many :videos, :source => :file, :through => :album_files, :source_type => "Viedo", :class_name => "Video"
end
class AlbumFile < ActiveRecord::Base
belongs_to :file, :polymorphic => true
end
class Photo < ActiveRecord::Base
has_many :album_files, :dependent => :destroy, :as => :file
has_many :albums, :source => :album, :foreign_key => "album_id", :through => :album_files, :class_name => "Album"
end
class Video < ActiveRecord::Base
has_many :album_files, :dependent => :destroy, :as => :file
has_many :albums, :source => :album, :foreign_key => "album_id", :through => :album_files, :class_name => "Album"
end


thats it..

Now we have associated Album with photos, videos through the mapping table album_files.

Following works for this

album = Album.create()
album.photos << Photo.create()
album.vidoes << Video.create()

album.album_files.count - returns the total count i.e, 2

album.photos - returns the count 1
album.vidoes - returns the count 1