As a SW/Ops/DB Engineer

riywo’s technology memo

Using Columns of a Intermediate Table With ActiveRecord Has_many Association

I have n:m relation tables and want to use columns of the intermediate table.

activerecord (4.0.0.rc2)

class User < ActiveRecord::Base
  has_many :user_bookmarks
  has_many :bookmarks, through: :user_bookmarks
end

class UserBookmark < ActiveRecord::Base
  belongs_to :user
  belongs_to :bookmark
  # has column "star"
end

class Bookmark < ActiveRecord::Base
  has_many :user_bookmarks
  has_many :users, through: :user_bookmarks
end

> User.first.bookmarks.first.star
NoMethodError: undefined method `star' for #<Bookmark:0x007ff40e45a7b8>

I used a scope block for has_many.

class User < ActiveRecord::Base
  has_many :user_bookmarks
  has_many :bookmarks, -> { select("bookmarks.*, user_bookmarks.star") }, through: :user_bookmarks
end

> User.first.bookmarks.first.star
10

I’m not sure whether this is the best way for the purpose, but it works.

Comments