作为一个真正的新手,我正在使用 RoR 构建一个非常简单的票务系统。
工单可以在我想通过关联连接的状态表中具有状态(例如“已确认”,ID 为“1”)。我想在视图中显示状态。代码如下。但我不断收到未定义的方法错误。也许我以错误的方式建立了关联?
票务.rb:
class Ticket < ActiveRecord::Base
belongs_to :user
belongs_to :state
状态.rb:
class State < ActiveRecord::Base
has_many :tickets
index.html.erb(基本上是脚手架):
<% @tickets.each do |ticket| %>
<tr>
<td><%= ticket.caller %></td>
<td><%= ticket.supervisor %></td>
<td><%= ticket.subject %></td>
<td><%= ticket.name %></td>
<td><%= ticket.email %></td>
<td><%= ticket.state.status %></td>
<td><%= link_to 'Anzeigen', ticket %></td>
<td><%= link_to 'Bearbeiten', edit_ticket_path(ticket) %></td>
<td><%= link_to 'Löschen', ticket, confirm: 'Sind Sie sicher?', method: :delete %></td>
门票控制器.rb
@tickets = Ticket.search(params[:search]).paginate(:page => params[:page], :per_page => 20)
这是它创建的 SQL 查询:
State Load (0.5ms) SELECT "states".* FROM "states" WHERE "states"."id" = 1 LIMIT 1
这会引发以下错误:
undefined method `status' for nil:NilClass
有趣的是,它似乎在 rails 控制台中工作:
1.9.3-p194 :016 > @tickets.state
State Load (0.5ms) SELECT "states".* FROM "states" WHERE "states"."id" = 2 LIMIT 1
=> #<State id: 2, status: "confirmed", created_at: nil, updated_at: nil>
1.9.3-p194 :017 > @tickets.state.status
=> "confirmed"