Add record to a has_and_belongs_to_many relationship

前端 未结 4 1004
天涯浪人
天涯浪人 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:16

    You can do just

    User.promotions = promotion #notice that this will delete any existing promotions
    

    or

    User.promotions << promotion
    

    You can read about has_and_belongs_to_many relationship here.

    0 讨论(0)
  • 2021-01-31 04:16

    This is also useful

    User.promotion.build(attr = {})
    

    so, promotion object saves, when you save User object.

    And this is

    User.promotion.create(attr = {})
    

    create promotion you not need to save it or User model

    0 讨论(0)
  • 2021-01-31 04:20
    user = User.find(params[:id])
    promotion = Promotion.find(params[:promo_id])
    user.promotions << promotion
    

    user.promotions is an array of the promotions tied to the user.

    See the apidock for all the different functions you have available.

    0 讨论(0)
  • 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
    => #<ActiveRecord::Associations::CollectionProxy [#<User id: 2 ...>]>
    
    0 讨论(0)
提交回复
热议问题