0

I have a many to many relastionship through join table :

team.rb

has_many :partners_teams
has_many :partners, through: :partners_teams

partner.rb

has_many :partners_teams
has_many :teams, through: :partners_teams

partners_team.rb

belongs_to :team
belongs_to :partner
self.primary_key = :partner_id
include RankedModel
ranks :row_order, with_same: :team_id
default_scope { order(row_order: :asc) }

I set an additional row "row_order" integer in the join table teams_partners

Partner is a nested resource of Team

How can I address the row_order column when I request the partners from a designed card, which happens in partners#index and cards#show

Currently, I do (it works correctly) :

Partners#index :

  def index
   @card = Card.find(params[:id])
   @partners = @team.partners.all
  end

Teams#show

def show
 @partners = @team.partners.all
end

I tried several things with joins and include but with no success. It's still a bit complicated to my level.

Moreover, I use Harvest ranked-model gem to sort my partners. It seems to work well except the initial order (problem described above). Thing is ranked-model use the .rank() method to order things. Ex: Partners.rank(:row_order). I'm not sure if that's a thing to take into account, I mean I can use an Partners.order(row_order: :desc), but maybe that'll have an impact for the following sorting.

Any help appreciated, really.

Thank you a lot.

Tamer Shlash
  • 9,314
  • 5
  • 44
  • 82
Mene
  • 344
  • 2
  • 14
  • 1
    Look at [this](http://stackoverflow.com/questions/2205618/how-do-i-order-a-has-many-through-association-in-ruby-on-rails). – Sergey Moiseev Jun 14 '14 at 21:53
  • Thank you for the answer Sergey. However, my row_order is in the join table, so scope doesn't seem to work for me. Moreover, I do not use the rank (:row_order) provided by Harvest (if it is necessary). Maybe a simple request in controller would do the job ? – Mene Jun 14 '14 at 22:57
  • 1
    So, things like [this](http://stackoverflow.com/a/6017567/511374) not working for you? – Sergey Moiseev Jun 14 '14 at 23:19
  • no, I'm on rails 4 so default_scope -> { order(row_order: :asc) } do the trick. But I'm still wondering why @partners = @team.partners.order('teams_partners.row_order') doesn't work since the sql look proper. I heard that the default scope is dangerous to use because it double the scope defined by rails. That's the reason why I want to avoid its use. But that seems work so... – Mene Jun 15 '14 at 00:04
  • http://rails-bestpractices.com/posts/806-default_scope-is-evil – Sergey Moiseev Jun 15 '14 at 00:06
  • has_many :partners, ->{ order 'partners_teams.row_order ASC' }, through: :partners_teams try it, show me your statements from console – Sergey Moiseev Jun 15 '14 at 00:13
  • It works well like this, I didn't use string but ashes. Thank you for your help ! How can I specify your comment as answer ? – Mene Jun 15 '14 at 00:19

0 Answers0