Nested Associations in Rails API -


quick question best practices apis.

i have user model belongs_to role model.

the role model has 2 possible predefined values: 'organizer' , 'judge'.

instead of creating new user normal rails way:

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

i'd users of api able create users so:

user: {     first_name: 'sample',     last_name: 'user',     role: 'organizer' } 

since have belongs_to: :role attached in user model, can't permit :role attribute in parameters , pass string, or error.

is there nice way in rails 4 without adding ton of code?

here's create action in 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 

i don't see why can't permit role parameter like

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

also, considering limited number of roles, maybe creating api endpoints each of them make sense or perhaps 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]) 

Comments

Popular posts from this blog

facebook - android ACTION_SEND to share with specific application only -

python - Creating a new virtualenv gives a permissions error -

javascript - cocos2d-js draw circle not instantly -