Skip to content

Instantly share code, notes, and snippets.

@veganstraightedge
Created December 3, 2015 20:50
Show Gist options
  • Save veganstraightedge/225e5fd5c66ba29664ea to your computer and use it in GitHub Desktop.
Save veganstraightedge/225e5fd5c66ba29664ea to your computer and use it in GitHub Desktop.
Is there a Railsy way of doing this kind of thing?
create_table "photos" do |t|
t.string "image_url"
t.integer "post_id"
end
create_table "posts" do |t|
t.string "title"
t.text "content"
end
create_table "videos" do |t|
t.string "video_url"
t.integer "post_id"
end
class Photo < ActiveRecord::Base
belongs_to :post
end
class Post < ActiveRecord::Base
has_one :video
has_one :photo
end
class Video < ActiveRecord::Base
belongs_to :post
end
Post.create!(title: "Test", content: "Lorem ipsum")
Photo.create!(image_url: "http://example.com/me.jpg", post_id: 1)
post = Post.first
post.title # => Test
post.content # => Lorem ipsum
post.photo.image_url # => http://example.com/me.jpg

I'd like to be able to call image_url, video_url, and other post-type specific attributes directly on post. For example:

post.title # => Test title
post.image_url # => http://example.com/me.jpg

Is there a Railsy way of doing this?

@searls
Copy link

searls commented Dec 3, 2015

Yes:

class Post < ActiveRecord::Base
  delegate :image_url, to: :photo
  delegate :video_url, to: :video
end

@swrobel
Copy link

swrobel commented Dec 3, 2015

What @searls said

@veganstraightedge
Copy link
Author

Thanks, @searls! That worked. I had to keep the has_one lines though.

class Post < ActiveRecord::Base
  has_one :video
  has_one :photo

  delegate :image_url, to: :photo
  delegate :video_url, to: :video
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment