我有两个类(class)用户和时间表:
class User < ActiveRecord::Base
attr_accessible :startdate, :schedule_id, :password, :username
belongs_to :schedule
end
class Schedule < ActiveRecord::Base
attr_accessible :name
has_many :users
end
我想创建一个 View ,在其中打印按用户过滤的对象计划的名称:
<table>
<% @users.each do |user| %>
<tr>
<td><%= user.id %></td>
<td><%= user.username %></td>
<td><%= user.password %></td>
<td><%= user.startdate %></td>
<td><%= Schedule.find(user.schedule_id).name %></td> # <<< This is what I want to do!
</tr>
<% end %>
</table>
当我执行此操作时,我收到“无法找到没有 ID 的时间表”
我该怎么做?感谢您的建议!
最佳答案
我看不出您的代码有任何语法错误。如果产生错误,请提供错误。要遵循 Ruby on Rails 约定,您应该能够执行以下操作:
<td><%= user.schedule && user.schedule.name %></td>
&&
是为了防止用户没有分配时间表。
关于ruby-on-rails - 查找带有 ID 的对象名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16004001/