【问题标题】:how to link_to between two different models如何在两个不同的模型之间链接到
【发布时间】:2017-11-12 13:55:36
【问题描述】:

我有两个模型,车辆模型和学生模型。我正在尝试从我的车辆索引视图链接到我的学生展示视图。但是,当我使用 link_to 时,我得到了 /students.0827312 的 url 的输出,并且我需要它作为 /students/0827312 在我的输出链接中,我不确定我错过了什么。我只是想弄清楚我需要调用什么来将 period 替换为 slash

车辆.rb

class Vehicle < ApplicationRecord
  self.primary_key = :vehicle_id
  belongs_to    :student, optional: true

学生.rb

class Student < ApplicationRecord
self.primary_key = :student_id
has_one :vehicle

/views/vehicles/index.html.erb

<%=link_to vehicle.student_id, students_path(vehicle.student_id) %>

rake route 命令

【问题讨论】:

  • 只是关于术语的注释,您不会在模型之间进行链接。模型是不知道什么是链接的后端概念。您在概念上链接 actions,它们是请求的前端处理程序。

标签: ruby-on-rails link-to


【解决方案1】:

students_path(vehicle.student_id) 必须是 student_path(vehicle.student.id)。单数,因为您链接到 student 的实例,而不是复数。

您将 ID 作为:format 传递给students_path,用于查看学生的索引,而不是特定学生。

【讨论】:

  • 当我在没有's'的情况下通过时,它表示该路线不存在?
  • 它确实存在,根据您发布的路线。最左边一列student是helper名称,表示student_pathstudent_url存在,路由/student/:idstudents#show
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2014-05-21
  • 1970-01-01
  • 2017-11-21
  • 2021-05-23
  • 1970-01-01
  • 1970-01-01
  • 2015-03-23
相关资源
最近更新 更多