我遇到一个问题,让两个用户属于同一型号(Ticket)。
在我正在构建的bug跟踪器中,Ticket是需要对项目执行的单个任务项。它附有两个用户,Ticket.raised_by和Ticket.assigned_to。创建用户
问题是我始终在ActiveRecord::AssociationTypeMismatch
操作上抛出Tickets#create
异常,并显示类似
User(#81485590) expected, got String(#68375030)
以下是Ticket.rb
的代码:
# Table name: tickets
#
# id :integer not null, primary key
# title :string(255)
# description :text
# status :string(255) default("open")
# priority :boolean default(FALSE)
# project_id :integer
# raised_by_id :integer default(0)
# assigned_to_id :integer default(0)
# created_at :datetime
# updated_at :datetime
class Ticket < ActiveRecord::Base
validates :title, :presence => true
validates :status, :presence => true
belongs_to :project
belongs_to :raised_by, :foreign_key => 'raised_by_id', :class_name => 'User'
belongs_to :assigned_to, :foreign_key => 'assigned_to_id', :class_name => 'User'
before_create do
self.raised_by = current_user
end
state_machine :status, :initial => 'open' do
# when a ticket is "claimed" by a developer
event :work do
transition any => :working_on
end
# posted the solved ticket to the dev server (or VM)
event :post do
transition any => :posted
end
# ticket is under review by another developer
event :review do
transition any => :reviewed
end
# review is completed and confirmed. only reviewed or flagged tasks can be completed.
event :complete do
transition [:review, :flagged] => :completed
end
# occurs when the project is completed
event :close do
transition any => :closed
end
# Special treatment for administrators. Sends them a Message detailing the flagged issue.
event :flagged do
transition any => :flagged
end
end
end
答案 0 :(得分:2)
我不知道您的身份验证是如何设置的,但我的猜测是您的模型无权访问current_user
,因此此代码失败:
before_create do
self.raised_by = current_user
end
有一些方法可以访问模型中的current_user
,但是存在一些风险(例如,它不是线程安全的)。有关示例,请参阅Access current_user in model。
但是,您可能希望在控制器中处理此问题,而不是使用挂钩来设置用户:
@ticket = Ticket.create(:raised_by => current_user, .....)
答案 1 :(得分:0)
也许current_user
是一个字符串?
它是如何进入模型的?用户会话是控制器业务。
答案 2 :(得分:0)
在您的表单上,您是否有任何机会拥有一个“已分配到”字段(可能是一个选择框),每个用户的名称为每个值? 如果是这样,当你在控制器中update_attributes时,它会尝试将该字段的字符串值放入assigned_to关联中,这会打破你的错误 我描述过。
将字段重命名为“assigned_to_id”,并确保字段的值是每个相应用户的ID,而不是其名称。