【问题标题】:ruby/rails variable scope before assignment分配前的 ruby​​/rails 变量范围
【发布时间】:2014-02-28 21:53:29
【问题描述】:

更新:

谢谢大家,继续:

def add_minor
  if @user.minors.count <= 2
    render :json =>  @user.profile.minors << Minor.find(params[:minor_id]), :status => 200
  else
    render :json => '', :status => 409
  end
end 

有没有更好的方法来处理这里 res 属性的分配以保持它可用于渲染调用?总的来说,我只是想知道如何改进这种非常臭的方法。

respond_to :json
def add_minor
  res = ''
  unless @user.minors.count > 2
    minor = Minor.find(params[:minor_id])
    res =  @user.profile.minors << minor
    status = 200
  else
    status = 409
  end
  render :json => res, :status => status
end

【问题讨论】:

  • 这将是一个见仁见智的问题,但我不会在resstatus 的这种简单情况下使用变量。我会颠倒逻辑并使用ifunless-else 让我的大脑受伤)。所以if @user.minors.count &lt;= 2 后跟render :json =&gt; @user.profile.minors &lt;&lt; minor, :status =&gt; 200else 就是render :json =&gt; '', :status =&gt; 409。我认为整个内容会更清晰,更易于阅读。

标签: ruby-on-rails activerecord active-model-serializers


【解决方案1】:
def add_minor
  if @user.minors.count > 2
    render :json => '', :status => 409
  else
    @user.profile.minors << Minor.find(params[:minor_id])
    render :json => @user.profile.minors, :status => 200
  end
end

【讨论】:

    猜你喜欢
    • 2023-03-03
    • 1970-01-01
    • 2013-05-22
    • 2013-11-10
    • 2017-03-11
    • 2011-10-20
    • 2022-01-17
    • 2015-07-11
    • 1970-01-01
    相关资源
    最近更新 更多