本文介绍了关联问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有 3 个模型 User、Club 和 Mcq.

I have 3 models User, Club and Mcq.

在俱乐部模型中.我将俱乐部(班级)指定为 -

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

  1. 9-物理
  2. 9-化学
  3. 10 物理
  4. 10-化学...

这是我的协会

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

在我的学生视图(学生展示索引)中,我显示所有俱乐部(作为主题),点击一个主题后,我只想显示该相关主题的 Mcq 主题.

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

所以我的问题是,当我点击主题物理时,它会显示所有 9 的 Mcq.化学也是一样.

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

我只想根据主题过滤 Mcq.

I just want to filtered Mcq according to subject.

推荐答案

您必须在您单击的主题链接中发送一个 params 作为 club_id.例如.<%=link_to "Subject", x_path(club_id: n) %> 然后你可以在你的控制器动作中捕捉这个参数作为 params[:club_id].然后重写控制器动作如下

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

不是,如果尚未添加,您可能需要在控制器中允许 club_id 此参数.希望这会帮助你.如果有任何问题,请告诉我?

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?

这篇关于关联问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 13:10