【问题标题】:How to create nested models from API request?如何从 API 请求创建嵌套模型?
【发布时间】:2014-06-25 21:39:06
【问题描述】:

我有一个 Rails API,我有两个模型:

class Event < ActiveRecord::Base

  belongs_to :category

  has_many :event_categories
  has_many :events, through: :event_categories

  attr_accessible :title, :description, :event_categories_attributes

  accepts_nested_attributes_for :event_categories

end

class EventCategory < ActiveRecord::Base

  belongs_to :event
  belongs_to :category

  attr_accessible :category_id, :event_id, :principal

  validates :event, :presence => true
  validates :category, :presence => true

  validates_uniqueness_of :event_id, :scope => :category_id

end

一开始,EventCategory 并不存在,所以我创建了事件资源发送参数,如event[title]='event1', event[description] = 'blablbla' 认为 POST REST 请求。

我的 API EventsController 是这样的(我没有新方法,因为我不需要视图):

 def create
    @event = Event.create(params[:event])
    if @event
      respond_with @event
    else
      respond_with nil, location: nil, status: 404
    end
  end

这种方式对我来说是正确的。现在,有了新的 EventCategory 模型,我不知道如何同时创建 EventCategories 模型。

我正在尝试这个......但它不起作用:

  def create
    @event = Event.new(params[:event])
    @event.event_categories.build
    if @event.save
      respond_with @event
    else
      respond_with nil, location: nil, status: 404
    end
  end

Rails 告诉我:

{
    "event_categories.event": [
        "can't be blank"
    ],
    "event_categories.category": [
        "can't be blank"
    ]
}

我这样发送category_id

event[event_categories_attributes][0][category_id] = 2

有什么想法吗?

【问题讨论】:

  • 你能告诉我们你的参数哈希吗?
  • (rdb:1) p 参数 {"event"=>{"title"=>"blabalb", "description"=>"mas baksldbadbnlas", "event_categories_attributes"=>{"0" =>{"category_id"=>"1"}}}, "access_token"=>"24cd498338b8f305dc925d9fba319ad05f258f1ec0869d676bb35fea9930ce8c", "format"=>"json", "a ction"=>"create", "controller"=>"api /v1/events"} (rdb:1)

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


【解决方案1】:

在您的 create 操作中,而不是这样:

@event.event_categories.build

试试这个:

@event.event_categories = EventCategory.new do |ec|
    ec.event = @event
    ec.category = the_cattegory_you_want_to_specify
    # You need both of these as you are validating the presence of event AND category
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    • 2012-11-04
    • 2016-11-25
    • 1970-01-01
    • 2012-02-29
    相关资源
    最近更新 更多