ruby on rails - How can i get the value of primary_value in activerecord has_many definition? -
# == schema information # # table name: books # id :integer # owner_id :integer # table name: users # id :integer # name :string # table name: shared_books_records # user_id :integer # book_id :integer books id: 1, owner_id: 1 # jack id: 2, owner_id: 2 # tom id: 3, owner_id: 1 # jack users id: 1, name: "jack" id: 2, name: "tom"
jack has 2 books , tom has 1 book.
shared_books_records user_id: 1, book_id: 2
so jack borrowed tom's book. jack should have 3 books.
class user def all_books join_sql = <<-sql.squish! left outer join shared_books_records on shared_books_records.user_id = books.assignee_id sql condition = <<-sql.squish! books.owner_id = :user_id or shared_books_records.user_id = user_id sql book.joins(join_sql).where(condition, user_id: id) end end
i think it's not good, activerecord
association better. want redefine it.
has_many :all_books, -> { primary_key_value = xxxx # want value join_sql = <<-sql.squish! left outer join shared_books_records on shared_books_records.user_id = books.assignee_id sql condition = <<-sql.squish! books.owner_id = :user_id or shared_books_records.user_id = user_id sql joins(join_sql).unscope(:where).where(condition, user_id: primary_key_value) }, class_name: book, foreign_key: :owner_id
but don't know how value of primary_key
in scope.
my solution
has_many :all_books, -> (user) { primary_key_value = user.id # want value join_sql = <<-sql.squish! left outer join shared_books_records on shared_books_records.user_id = books.assignee_id sql condition = <<-sql.squish! books.owner_id = :user_id or shared_books_records.user_id = :user_id sql joins(join_sql).unscope(:where).where(condition, user_id: primary_key_value) }, class_name: book, foreign_key: :owner_id
to books can this
class user has_many :user_books has_many :books, through: :user_books end class userbook belongs_to :books belongs_to :users end class book has_many :user_books has_many :users, through: :user_books end # table name: books # id :integer # owner_id :integer # table name: users # id :integer # table name: user_books (previously shared_books_record) # user_id :integer # book_id :integer def all_ books #lets id has value user_id user = user.find(id) all_books = user.books #this should return array of books belongs current user end
Comments
Post a Comment