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?
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 |
What @searls said
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
Yes: