如何从控制器向序列化器发送参数?

时间:2016-05-30 18:48:17

标签: ruby-on-rails ruby rails-activerecord

我对Rails很新。我的控制器中有以下索引功能:

def index
  @trip_styles = TripStyle.all
  render json: @trip_styles
end

这是我的序列化器:

class TripStyleSerializer < ActiveModel::Serializer
  attributes :id,
             :name,
             :trip_style_tag_id,
             :resource,
             :quantity

  def quantity
    for client_tag_quantity in object.marketing_client_tag_quantity
      object = client_tag_quantity.quantity
    end
    return object
  end
end

我想从我的控制器向我的序列化器发送一个新参数agent,但我不能这样做。我试过了:

@trip_styles.each do |style|
  style[:agent] = @current_agent.id
end

它显示此错误:ActiveModel::MissingAttributeError (can't write unknown attribute 'agent')

感谢。任何帮助将不胜感激

2 个答案:

答案 0 :(得分:1)

我想说你的模型中存在缺失的关系,或者agent_id不属于你的旅行风格对象(因此不应该被序列化为旅行风格对象的一部分)。所以我认为你有一个设计问题,我们需要更多的信息来帮助你。

如果你想快速入侵,你可以在控制器中做到

选项1:直接添加到可序列化哈希

def index
  @trip_styles = TripStyle.all
  render json: serialize_trip_styles
end

private 
def serialize_trip_styles
  @trip_styles.map { |ts| ts.to_h.merge(agent: @current_agent.id) }
end

选项2:向TripStyleSerializer

添加初始化参数
private 
def serialize_trip_styles
  @trip_styles.map do |ts|
    TripStyleSerializer.new(ts, agent: @current_agent.id)
  end
end

您需要使用此方法相应地修改旅行样式类:

class TripStyleSerializer < ActiveModel::Serializer
  attributes :agent
  def initialize(object, options={})
    @agent = options[:agent]
    super(object, options)
  end

另外,作为附注,我建议您不要在活动模型序列化程序中使用变量名object,因为它与继承自ActiveModel::Serializerobject属性冲突

def quantity
  for client_tag_quantity in object.marketing_client_tag_quantity
    # Bad use of object as a variable name
    object = client_tag_quantity.quantity
  end
  return object
  # Btw, this will loop through all the elements and affects the last 
  # item of object.marketing_client_tag_quantity to object
  # which doesn't look like something you want to do
  # If you want to do that though, just 
  # return object.marketing_client_tag_quantity.last.quantity
end

答案 1 :(得分:0)

非常确定您需要将:agent添加到属性列表中。

class TripStyleSerializer < ActiveModel::Serializer
  attributes :id,
             :name,
             :trip_style_tag_id,
             :resource,
             :quantity,
             :agent

  def quantity
    for client_tag_quantity in object.marketing_client_tag_quantity
      object = client_tag_quantity.quantity
    end
    return object
  end
end