【问题标题】:write a efficient code in controller [closed]在控制器中编写有效的代码[关闭]
【发布时间】:2014-02-07 18:25:25
【问题描述】:

我有一个控制器,其中包含许多路由到不同页面的操作

def act1
 @a=...
 @b=....
 @c=...
end

def act1
 @a=...
 @b=....
 @c=...
end

def act2_ajax
 @a=...
 @b=....
 @c=...
end

def act3
 @a=...
 @b=....
 @c=...
end

def act4_ajax
 @a=...
 @b=....
 @c=...
end

我想在一个单独的动作中编写这些变量并只调用动作名称,我在视图中使用了变量@a,@b @c,所以如果我调用一个单独的动作,这些变量应该会出现

例如,假设我们写了

def common(xx)
  @a=...
  @b=...
  @c=...
end

我们在act1中调用common like

def act1
  self.common1(var)
end

哪个输出像

def act1 
  @a=...
  @b=...
  @c=...
end

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 coding-style


    【解决方案1】:
    before_action :set_vars, only: [:act1, :act2, :act3]
    
    private
      def set_vars
        @a = ...
        @b = ...
        @c = ...
      end
    

    而且你的动作中没有额外的线条!

    【讨论】:

    • 问题被标记为ruby-on-rails-3 并且before_action 已在Rails 4.0.0 中引入,所以您的意思可能是before_filter
    猜你喜欢
    • 1970-01-01
    • 2011-04-23
    • 1970-01-01
    • 2016-08-26
    • 2014-08-20
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多