从控制器传递到模型

时间:2016-06-01 08:23:25

标签: ruby-on-rails ruby ruby-on-rails-4

RoR很新。不知道有没有人可以帮我解决这个问题。

我有一个名为“business_time”的宝石,用于计算两个日期之间的营业日。我在模型中设置了一个完成所有计算的方法。

我有一个名为“credit”的字段,该字段应该包含工作日的数量。这就是我所拥有的:

MODEL

def self.calculate(from_date,to_date)
   days = 0

   date_1 = Date.parse(from_date)
   date 2 = Date.parse(to_date)
   days = date_1.business_days_until(date2)

   days
end

CONTROLLER

def new
   @vacation = current_user.vacations.build
   @vacations = Vacation.calculate(:from_date, :to_date)
end

我引用了一个关于字符串的错误。

此外,如何将方法中的数据存储到名为“credit”的字段中?

谢谢你们。

2 个答案:

答案 0 :(得分:1)

您需要的是传递String个对象而不是Symbol个对象。

因此,您可能需要传递@vacations = Vacation.calculate(:from_date, :to_date)params[:from_date]而不是params[:to_date],而不是20/01/2016,而不是@vacations = Vacation.calculate(params[:from_date], params[:to_date])

您的代码应为

=Lookup(Fields!Postcode.Value,Fields!ID.Value,Fields!Name.Value,<b>"DataSet1"</b>)

答案 1 :(得分:1)

我认为不需要额外的方法,因为所有属性(from_dateend_datecredit)都存储在同一个模型中。

我只需在初始化程序中设置from_dateend_date,然后在验证前使用回调计算credit

# in the model
before_validation :calculate_credit

private
  def calculate_credit
    if from_date && to_date
      # `+ 1` because the user takes off both days (`from_date` and `to_date`),
      # but `business_days_until` doesn't count the `from_day`. 
      self.credit = from_date.business_days_until(to_date) + 1
    end
  end

# in the controller
def new
  @vacation = current_user.vacations.build
end

def create
  @vacation = current_user.vacations.build(vacation_params)

  if @vacation.save
    # @vacation.credit would return the calculated credit at this point
  else
    # ...
  end
end

private
  def vacation_params
    params.require(:vacation).permit(:from_date, :to_date)
  end
相关问题