rails update方法不调用类方法

时间:2013-10-30 21:18:28

标签: ruby-on-rails controller

我有一个类方法,我需要调用一个名为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

Class 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>

当params中的值为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

1 个答案:

答案 0 :(得分:0)

有些事情是错误的:

首先,您需要在条件中调用@virtual_request.auto_assign!,因为否则不会设置artist_id。

其次,当您在auto_assign方法中进行更改时,不要忘记save更新的实例:

def update
  @virtual_request = VirtualRequest.find(params[:id])

  if @virtual_request.update(virtual_params)
    @virtual_request.auto_assign!
    @virtual_request.save
    flash[:success] = "Virtual request updated"
    redirect_to virtual_request_path(@virtual_request)
  else
    render 'edit'
  end
end

这些方面的内容,但我相信其他人会提出更有效的解决方案

或者您的方法(使用此方法,您不需要控制器中的save。)

def auto_assign!
  if self.artist_id == 0
    artists = Artist.in_queue?.collect {|p| [ p.id, p.virtual_requests.count ] } 
    artist_id = artists.sort { |a,b| a[1] <=> b[1] }.first[0]
    self.update_attribute(:artist_id,artist_id)
  end
end

无论如何都要玩一些东西!