Association Issue

2019-08-06 10:06发布

问题:

I have 3 models User, Club and Mcq.

In club model. I assign club (class) as -

  1. 9-physics
  2. 9-chemistry
  3. 10-physics
  4. 10-chemistry...

Here is my Association

class User < ActiveRecord::Base
  has_and_belongs_to_many :clubs
end

class Club < ActiveRecord::Base
  has_many :mcqs
  has_and_belongs_to_many :users
end

class Mcq < ActiveRecord::Base
    belongs_to :club
end

In my student view (student show index) I show all club (as subject) and after click on a subject I just want to show Mcq topic of that related subject.

for that my Club Controller is -

class ClubsController < ApplicationController

#its show subject list
def student_show_index
    @club = current_user.clubs
  end

  #its show topic according to subject.
  def student_show_topic
    @club = current_user.clubs
    @mcq = @club.first.mcqs.order('created_at DESC')
  end

end

So my question is, when I click on subject physics it show all the Mcq of 9th. and same for chemistry.

I just want to filtered Mcq according to subject.

回答1:

You have to send a params as club_id in the link of subject which you are clicking. eg. <%=link_to "Subject", x_path(club_id: n) %> Then you can catch this params in your controller action as params[:club_id]. then rewrite the controller action as following

def student_show_topic
  @club = Club.find(params[:club_id])
  @mcq = @club.mcqs.order('created_at DESC')
end

Not you may need to permit club_id this params in your controller, if not yet added. Hope this will help you. Let me know if any issues?