小编zer*_*sor的帖子

ActiveModel :: Serializer是否需要显式渲染调用?

我知道在使用视图模板(html,rabl)时,我不需要在我的控制器操作中进行显式渲染调用,因为默认情况下,Rails会使用与控制器操作名称对应的名称来呈现模板.我喜欢这个概念(不关心我的控制器代码中的渲染),因此想知道在使用ActiveModel :: Serializers时这是否可行?

例如,这是来自生成的控制器的代码(Rails 4.1.0):

class ProductsController < ApplicationController
  before_action :set_product, only: [:show, :edit, :update, :destroy]

  #other actions
  # GET /products/1
  # GET /products/1.json
  def show
  end
end
Run Code Online (Sandbox Code Playgroud)

这是序列化器:

class ProductSerializer < ActiveModel::Serializer
  attributes :id, :name, :description, :url, :quantity, :price
end
Run Code Online (Sandbox Code Playgroud)

点击/products/1.json,我希望有两件事情发生:

  1. 未列出序列化程序中未列出的字段,
  2. 要在"产品"顶级字段中封装的整个JSON对象.

但是,这不会发生,整个序列化器被忽略.但是,如果我将Show方法修改为以下内容:

# GET /products/1
# GET /products/1.json
def show
  @product = Product.find(params[:id])
  respond_to do |format|
    format.html
    format.json { render json: @product }
  end
end
Run Code Online (Sandbox Code Playgroud)

现在一切都很好,但我已经失去了before_action过滤器的好处(在我看来,我有一些冗余代码).

这应该怎么做?

actioncontroller active-model-serializers ruby-on-rails-4

5
推荐指数
1
解决办法
1240
查看次数

Ruby中的条件块

假设我有with_foo一个带块的函数,并将它包装在一段代码中,比如

with_foo do
  puts "hello!"
end
Run Code Online (Sandbox Code Playgroud)

现在我想使包装有条件,如

if do_with_foo?
  with_foo do
    puts "hello!"
  end
else
  puts "hello!" # without foo
end
Run Code Online (Sandbox Code Playgroud)

有没有办法写这个更短/更优雅,意味着不必重复代码puts "hello!"

ruby

4
推荐指数
1
解决办法
3904
查看次数

Ruby 的 Array#insert 的复杂度是多少?

Ruby 的 Array#insert 的复杂度是多少?

是 O(1) 还是 O(n)(内存被复制)?

ruby

3
推荐指数
1
解决办法
744
查看次数