【问题标题】:Association Issue协会问题
【发布时间】:2015-09-21 16:31:19
【问题描述】:

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

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

  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 主题。

因为我的俱乐部控制器是 -

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。和化学一样。

我只是想根据主题过滤 Mcq。

【问题讨论】:

    标签: ruby ruby-on-rails-4


    【解决方案1】:

    您必须在您点击的主题链接中以club_id 的形式发送params。例如。 &lt;%=link_to "Subject", x_path(club_id: n) %&gt; 然后您可以在控制器操作中将此参数捕获为params[:club_id]。然后重写控制器动作如下

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

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

    【讨论】:

    • 哇。它的工作很棒,对我很有帮助。 bcoz 我是 RoR 的新手。我只是得到一个后退按钮的问题。我会管理它。非常感谢。
    • 申请 MCQ 评估后,我转到 Mcq 控制器。 n 在那里我显示 mcq 的问题,在该页面中我有一个返回按钮的链接 "button" %> 但点击该链接后我得到错误- 找不到带有 'id'=#<:activerecord_associations_collectionproxy:0x007f320cfff1a0> 的俱乐部 [WHERE clubs_users.user_id = ?] 提取源(在第 80 行附近):def student_show_topic 80 @club = current_user.clubs .find(params[:id]) @mcq = @club.mcqs.order('created_at DESC') 结束
    • 这个 cmets 部分不是很清楚,但似乎是 @club = current_user.clubs.find(params[:id]) 这个语句中的问题,尝试将其重写为 @club = current_user.clubs.where(id: params[:id]).first 或 @club = Club.where("id =? AND user_id=?", params[:id], current_user.id).first
    • 我在 Mcq 控制器的 def apply 中写了 '@club = current_user.clubs.where(id: params[:id]).first'。然后得到错误 - ** ActionController::UrlGenerationError in Mcqs#apply ** '没有路线匹配 {:action=>"student_show_index", :controller=>"clubs", :id=>nil} 缺少必需的键:[:id ]'
    猜你喜欢
    • 2021-11-04
    • 1970-01-01
    • 2011-07-07
    • 2015-06-20
    • 2012-10-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多