使用button_to更新多个值 - Rails 4

时间:2014-06-04 04:14:46

标签: ruby-on-rails ruby controller

我在使用Rails中的按钮更新表格中的列时遇到问题。 我已经查看了stackoverflow的答案,但似乎无法正常工作......

在我的应用中,我希望用户能够"租用"并且"返回"引脚。 当他们点击" Rent"按钮,我希望它改变别针的列。

示例:租借:=> true,renter_id:1"

在我的Pins控制器中:

def rent
@pin = Pin.update_attribute(:renter_id => @user.id)
end

在我的观点中:

<%= button_to "Rent Now!", {:controller => "pins", :action => "rent", :renter_id => @user.id }, :class => 'btn btn-success btn-lg btn-block'%>

架构:

create_table "pins", force: true do |t|
t.string   "description"
t.string   "link"
t.boolean  "rented"
t.integer  "renter_id"
end

2 个答案:

答案 0 :(得分:3)

一个问题是update_attribute是一种实例方法。但是你试图在Pin上将其称为类方法。也许做一个像这样的控制器。

def rent
  @pin = Pin.find(params[:id])
  if @pin.update_attributes(renter_id: @user.id)
    #handle success
  else
    #handle failure
  end
end

还要确保您的路线已正确设置为发布请求。

答案 1 :(得分:2)

update_attribute有2个参数,属性和值

所以应该是这样的

update_attribute(:renter_id, @user.id)

如果您想一次更新多个属性,或者想要触发验证,请使用update_attributes

update_attributes(:attr1 => value1, :attr2 => value2)