【问题标题】:Nested attributes in a JSON with Rails 3使用 Rails 3 在 JSON 中嵌套属性
【发布时间】:2013-06-13 23:47:21
【问题描述】:

我有以下关联:

活动 has_many 行程
旅行 belongs_to 活动
旅行 has_many 活动
活动 belongs_to 旅行

在我的 API 中,我接受对如下所示 URL 的 POST 请求:

/campaigns/1/trips

传递 JSON 的位置。 JSON 如下所示:

{"trip":{"red":3, "blue":400, "events_attributes":[{"distance":300}, {"distance":400}]}}

我的事件控制器的#create 操作如下所示:

 def create
     begin
         @campaign = @user.campaigns.find(params[:campaign_id])
         @trip = @campaign.trips.create(params[:trip])
         render json: @trip, :status => :ok
     rescue
         render json: '', :status => :not_found 
     end
 end

在我的 Trip 模型中,我添加了这一行:

   accepts_nested_attributes_for :events

所以,我期待旅行将使用相应的事件创建,但我得到的是 401 未找到。如果我没有通过 events_attributes,则行程会正确创建。

我已经根据这个问题制定了这个解决方案:Nested object creation with JSON in Rails

对我做错了什么有什么想法吗?

【问题讨论】:

  • 嗯,您正在挽救 any 错误并返回 401,这意味着您可能没有看到代码的实际异常正在生产。尝试删除begin/rescue/end,然后在您的问题中包含异常(除非在您看到真正的错误后解决方案变得明显)。
  • MrTheWalrus,到底发生了什么。谢谢:P

标签: ruby-on-rails ruby-on-rails-3 nested-attributes


【解决方案1】:

我捕捉到了错误的异常,这让我很困惑。

我遇到了批量分配错误,因为无法从 Trip 模型访问 events_attributes,但我错误地将其视为未找到的异常。

我在 Trip 模型中添加了这一行:

attr_accessible :events_attributes

它就像一个魅力:)

哦,顺便说一句,我在救援中添加了这个:

rescue ActiveRecord::RecordNotFound

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多