【问题标题】:How to perform a method in model only if the controller action is create?仅当创建控制器操作时如何在模型中执行方法?
【发布时间】:2015-04-10 01:14:23
【问题描述】:

问题在我的 Rails 应用程序中我有一个名为 range days 的方法我只希望它在控制器操作是 create_half 的情况下工作我该怎么做?任何帮助将不胜感激!!

这是我的入门模型

class Entry < ActiveRecord::Base

  self.primary_key = 'id'

  //This is what I want to only happen when my controller action is create_half 
  def range_days
    self.range_days = only_weekdays(leave_start.to_date..(leave_end.to_date)).to_d 
  end

这是我的入口控制器

 class EntryController < ApplicationController


   def half_day
     @entry = Entry.new
     render :half_day
   end

【问题讨论】:

  • This is what I want to only happen when my controller action is create_half 是什么意思? range_days 是一个实例方法,可用于Entry 的任何实例。
  • 是的 @Sharvy Ahmed 我怎样才能让 range_days 只能用于创建?
  • 我不建议将方法调用为与你们中的一个属性相同的东西。这现在已成为隐蔽分配,每次调用时都会重置range_days。这会让以后的调试非常混乱。
  • 所以如果我更改了 range_days 方法的名称,我只能在创建正确时调用它?
  • 不要保持属性和方法名称相同。如果您尝试从该方法内部调用该属性,您将陷入无限循环。

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


【解决方案1】:

将您的属性名称从 range_days 更改为其他名称。否则你将无法获得range_days action 中的值。

range_days 方法中的self.range_days 将再次调用range_days 方法而不是range_days 属性。结果它会变成一个无限循环,你会得到一个Stack Level Too Deep异常。

然后您可以在控制器中简单地执行以下操作:

def create_half 
  @entry = Entry.new
  @entry.range_days
  ...
end

【讨论】:

    【解决方案2】:

    我假设您正在寻找一种有条不紊的方式来做到这一点。它不需要:

    class EntryController < ApplicationController
      def create_half
        @entry = Entry.new.range_days
        #other stuff
      end
    end
    

    你应该没事吧。

    【讨论】:

    • 我在尝试您的 answeapp/controllers/entry_controller.rb:60 时收到此错误:语法错误,意外 tIVAR,期待 ')' @entry = Entry.new.t_days ^
    • 语法错误在您的代码中,而不是我的示例。如果您还没有找到代码,请发布代码。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-18
    • 2011-02-07
    • 1970-01-01
    • 2017-01-03
    • 2011-08-26
    相关资源
    最近更新 更多