【发布时间】:2016-05-26 20:50:55
【问题描述】:
版本:CENTOS7、mysql2('>= 0.3.13'、'
index.html.erb
<% @sections.each do |section| %>
<tr>
<td><%= section.course_id %></td>
<td><%= section.term_id %></td>
<td><%= section.user_id %></td>
</tr>
<% end %>
部分控制器
class SectionsController < ApplicationController
before_action :authenticate_account!, except: [:show]
def index
@sections = User.find_by_account_id(current_user).courses
end
def show
end
end
createSections 迁移
class CreateSections < ActiveRecord::Migration
def change
create_table :courses do |t|
t.integer :course_id
t.timestamps null: false
end
create_table :terms do |t|
t.integer :term_id
t.timestamps null: false
end
create_table :users do |t|
t.integer :user_id
t.timestamps null: false
end
create_table :sections do |t|
t.belongs_to :course, index: true
t.belongs_to :term, index: true
t.belongs_to :user, index: true
t.timestamps null: false
end
end
end
course.rb 模型
belongs_to :user
has_many :sections
has_many :terms, :through => :sections
term.rb 模型
belongs_to :user
has_many :sections
has_many :courses, :through => :sections
section.rb 模型
belongs_to :course
belongs_to :term
belongs_to :user
user.rb
has_many :sections
has_many :courses, :through => :sections
has_many :terms, :through => :sections
- 预期结果:列出当前(登录)用户的课程/术语/ID
- 当前结果:空白
这是我第一次使用 rails 和 SO,我尝试了几次更改关系以查看是否会发生任何变化,但不知道如何解决这个问题。我尝试使用 ActiveRecord:Associations 作为参考。我需要做什么才能完成这项工作?
【问题讨论】:
-
你正在分配
@sections = current_user.courses——你的意思是@sections = current_user.sections吗? -
我喜欢你顺便描述你的问题 :thumbsup:
-
-
已经有了用户
current_user,为什么还要查询用户? -
也许我误会了我的意图,当我加载我的 /sections 页面时我想要发生的事情是为了显示当前登录用户的“结果”,即。其中他的 user_id 与 course_id、term_id 匹配。例如,老师会教一些课程,这会显示老师在此页面中教授的课程以及条款。
标签: ruby-on-rails ruby activerecord arel