s_dolan
s_dolan

Reputation: 1276

Nested Associations in Rails API

Quick question about best practices for APIs.

I have a User model that belongs_to a Role model.

The Role model has two possible predefined values: 'Organizer' and 'Judge'.

Instead of creating a new User the normal Rails way:

user: { 
    first_name: 'Sample', 
    last_name: 'User', 
    role: { 
        id: 1, 
        label: 'organizer' 
} }

I'd like the users of my API to be able to create users like so:

user: {
    first_name: 'Sample',
    last_name: 'User',
    role: 'organizer'
}

Since I have the belongs_to: :role attached in my User model, I can't permit the :role attribute in my parameters and then pass it a string, or I get an error.

Is there some nice way to do this in Rails 4 without adding a ton of code?

Here's my create action in my UsersController:

def create
    @user = User.new( create_params )

    if @user.save
      render json: @user, status: :created
    else
      render json: @user.errors, status: :unprocessable_entity
    end
end

def create_params
    params.permit( :first_name, :last_name, :role )
end

Upvotes: 0

Views: 256

Answers (1)

errata
errata

Reputation: 26792

I don't see why you can't permit the role parameter then do something like

Role.where(:name => user_params[:role]).first << User.create(first_name => user_params[:first_name], :last_name = user_params[:last_name])

Also, considering the limited number of roles, maybe creating api endpoints for each of them would make sense or perhaps a catchall:

post '/api/v1/roles/:role_name' :to => 'user#create'

then:

Role.where(:name => params[:role_name]).first << User.create(first_name => user_params[:first_name], :last_name = user_params[:last_name])

Upvotes: 1

Related Questions