TicketsController #new中的ActiveRecord :: AssociationTypeMismatch

时间:2013-11-11 23:10:39

标签: activerecord ruby-on-rails-4

我有两个型号和控制器,一个用于用户,一个用于门票。

每个用户都可以拥有多张门票。每个管理员用户(由admin: true表示)可以分配许多票证。

以下是我的协会:

class Ticket < ActiveRecord::Base
  belongs_to :sender, class_name: "User", foreign_key: "id", inverse_of: :sent_tickets
  belongs_to :admin, class_name: "User", foreign_key: "id", inverse_of: :assigned_tickets

  .
  .
  .

end

class User < ActiveRecord::Base

  .
  .
  .

  has_many :sent_tickets, class_name: "Ticket", foreign_key: "sender", inverse_of: :sender, dependent: :nullify
  has_many :assigned_tickets, class_name: "Ticket", foreign_key: "assigned", inverse_of: :admin, dependent: :nullify

  .
  .
  .

end

但是,无论何时我尝试运行@ticket = user.sent_tickets.build(在Rails IRB中运行user = User.first之后,我都会ActiveRecord::AssociationTypeMismatch in TicketsController#new: User(#number) expected, got Fixnum(#number)

任何人都可以帮我吗?

1 个答案:

答案 0 :(得分:0)

修正了它。我将senderassigned重命名为sender_idassigned_id。然后我重写了我的协会:

class Ticket < ActiveRecord::Base
  belongs_to :assigned, class_name: "User"
  belongs_to :sender, class_name: "User"

  .
  .
  .

end

class User < ActiveRecord::Base

  .
  .
  .

  has_many :help_requests, foreign_key: "sender_id", class_name: "Ticket", dependent: :nullify
  has_many :sent_requests, through: :help_requests , source: :sender

  has_many :tickets, foreign_key: "assigned_id", dependent: :nullify
  has_many :assigned_tickets, through: :tickets, source: :assigned

  .
  .
  .

end