Rails 3 - 如何通过link_to增加值和更新数据库

时间:2012-02-14 17:58:25

标签: ruby-on-rails-3

我有一个观点:

<h2>The current billing period is <%= @current_period %></h2>
<h2>The current period approved is <%= @approval_period %></h2>
<h2><%= link_to "Approve Period", :method => :approve, :id => @approval_period %></h2>

和控制器:

def approval_period
  @current_period = PeriodCounter.first.period.pe_number
  @approval_period = ApprovalPeriod.first.period.pe_number
end

def approve
  @approval_period = ApprovalPeriod.first.period_id
  @approval_period.update_attribute("period_id", period_id + 1)
  @approval_period.save
  redirect_to :back
  flash[:notice] = "Approval Period Updated."
end

我正在尝试更新数据库,以便在点击链接时将@approval_period增加1。我已经离开Rails很长一段时间了,所以我知道我错过了一些关键元素。有帮助吗?提前谢谢......

2 个答案:

答案 0 :(得分:8)

:method不是控制器中的方法,而是HTTP动词,如Get或Post。相反,你应该做像

这样的事情
<%= link_to "Approve Period", approve_path(:period => @approval_period) %>

并将routes.rb中的approve_path添加为

match "/approve" => "controller#approve", :as => :approve

(以上是添加路线的一种方法,您可以learn how to add more restful routes

阅读Rails Routing from the Outside In以了解有关路由的更多信息。

<强>更新

@approval_period.update_attribute("period_id", period_id + 1)

上面的行是抛出错误的原因。您尚未在任何地方定义period_id。来自params[:period]的参数。

然后,你可以这样做:

方法1

@approval_period = ApprovalPeriod.find(params[:period]) 
@approval_period.update_attribute("period_id", @approval.period_id + 1)

方法2

用方法摘要:

class ApprovalPeriod < AR::Base
  def increment!
    # Here 'period_id' is valid since it is an attribute and a method 
    # with that name will be available
    update_attribute(:period_id, period_id + 1)
  end
end

在控制器中:

def approve
  @approval_period = ApprovalPeriod.find(params[:period])
  @approval_period.increment!
  ...
  # Other code here
end

随身携带任何套房。

答案 1 :(得分:0)

尝试这样的事情。

将此方法添加到ApprovalPeriod模型中。

class ApprovalPeriod < ActiveRecord::Base
  .
  .
  .
  def increase_period
    self.increase! :period
  end
end

控制器:

def approve
  @approval_period = ApprovalPeriod.find(params[:period_id])
  @approval_period.increase_period
  redirect_to :back
  flash[:notice] = "Approval Period Updated."
end