Question

I've a Rails API and I've two models:

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

and

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

In a first moment, EventCategory didn't exist so I created Event resources sending params like event[title]='event1', event[description] = 'blablbla' thought POST REST request.

My API EventsController was like this (I haven't a new method because I don't need views):

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

This way worked correctly for me. Now, with the new EventCategory model I don't know how I could create EventCategories models at the same time.

I've trying this... but it doesn't work:

  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 told me:

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

I send the category_id like this:

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

Any ideas?

Was it helpful?

Solution

In your create action, instead of this:

@event.event_categories.build

Try this:

@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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top