Add record to a has_and_belongs_to_many relationship

前端 未结 4 1012
天涯浪人
天涯浪人 2021-01-31 04:00

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         


        
4条回答
  •  梦谈多话
    2021-01-31 04:24

    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
    => #]>
    

提交回复
热议问题