我有一个类方法,我需要调用一个名为 auto_assign 的控制器更新方法!
它本质上是找到请求数量最少的艺术家,并将该艺术家 ID 分配给对象。
它在 create 方法上完美运行,但在 update 方法上没有被调用,我不知道为什么。
控制器
def update
@virtual_request = VirtualRequest.find(params[:id])
@virtual_request.auto_assign! # this never gets called
if @virtual_request.update_attributes(virtual_params)
flash[:success] = "Virtual request updated"
redirect_to virtual_request_path(@virtual_request)
else
render 'edit'
end
end
def create
@virtual_request = VirtualRequest.new(virtual_params)
@virtual_request.auto_assign! # works fine here!
if @virtual_request.save
flash[:success] = "Virtual has been created and assigned to # {@virtual_request.artist.name}"
redirect_to virtual_requests_path
else
render 'new'
end
end
类 VirtualRequest
def auto_assign!
if self.artist_id == 0
artists = Artist.in_queue?.collect {|p| [ p.id, p.virtual_requests.count ] }
self.artist_id = artists.sort { |a,b| a[1] <=> b[1] }.first[0]
end
end
HTML 发送参数
<select id="virtual_request_artist_id" name="virtual_request[artist_id]">
<option selected="selected" value="0">auto-assign</option>
<option value="2">Artist 1</option>
<option value="5">Artist 2</option>
</select>
它应该在参数中的值为 0 时自动分配
更新:已解决
控制器
def update
@virtual_request = VirtualRequest.find(params[:id])
if @virtual_request.update_attributes(virtual_params)
@virtual_request.auto_assign!
flash[:success] = "Virtual request updated"
redirect_to virtual_request_path(@virtual_request)
else
render 'edit'
end
end
班级
def auto_assign!
if self.artist_id == 0
artists = Artist.in_queue?.collect {|p| [ p.id, p.virtual_requests.count ] }
self.artist_id = artists.sort { |a,b| a[1] <=> b[1] }.first[0]
self.save
end
end