I have two models, users and promotions. The idea is that a promotion can have many users, and a user can have many promotions.
class User < ActiveRecord::Bas
If you want to add a User to a Promotion using a prototypical PromotionsController CRUD setup and you're not using Rails form helpers, you can format the params as:
params = {id: 1, promotion: { id: 1, user_ids: [2] }}
This allows you to keep the controller slim, e.g., you don't have to add anything special to the update
method.
class PromotionsController < ApplicationController
def update
promotion.update(promotion_params)
# simplified error handling
if promotion.errors.none?
render json: {message: 'Success'}, status: :ok
else
render json: post.errors.full_messages, status: :bad_request
end
end
private
def promotions_params
params.require(:promotion).permit!
end
def promotion
@promotion ||= Promotion.find(params[:id])
end
end
The result would be:
irb(main)> Promotion.find(1).users
=> #]>