【问题标题】:Best way to access a value from a database with Ruby on Rails使用 Ruby on Rails 从数据库中访问值的最佳方法
【发布时间】:2020-09-22 18:34:28
【问题描述】:

我正在创建一个教育管理系统,允许您使用 ruby​​ on rails 跟踪学生、班级、部门、部门、教授和学期。除sections_student 之外的每个表都是使用rails g 脚手架创建的。这是我目前的 ERD。 ERD

我正在尝试为学生编辑 _form.html.erb 以显示复选框,以便学生可以添加课程。我已经设置了它,它显示有课程,但他们没有显示课程编号。我相信它显示了课程对象的地址Student _form.html

这是我用来显示复选框的一段代码。我尝试将 :course 更改为 :course.number ,但它显示“用于 :course:Symbol 的未定义方法‘数字’”。 :

<div class="field">
  <%= form.label :section_id %>
  <%= form.collection_check_boxes(:section_ids, @sections, :id, :course) %>
</div>

我很困惑,因为在 students/show.html.erb 中,我可以在这里使用 section.course.number 轻松显示课程编号:

<ol>
 <% @student.sections.each do |section| %>
  <li><%=section.course.number%> Credit Hours: <%=section.course.hours%> <%=section.professor.name %> 
  </li>
 <% end %>
</ol>

这是Working course display的样子

如果您需要更多信息,请告诉我。谢谢!

【问题讨论】:

  • 它在这里抛出错误:&lt;%=section.course.number%&gt; - section.course 返回什么?它看起来像一个符号 :course,而不是 Course 的一个实例。

标签: html ruby-on-rails ruby


【解决方案1】:

现在collection_check_boxes 在每个部分都调用.course。您可能想致电course.number。实现此目的的一种方法是添加类似

def course_number
  course.number
end

到您的Section-Model,然后使用它:

<%= form.collection_check_boxes(:section_ids, @sections, :id, :course_number) %> 

【讨论】:

猜你喜欢
  • 2010-12-08
  • 2020-11-08
  • 2011-02-24
  • 2021-11-15
  • 1970-01-01
  • 2012-03-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多