Add record to a has_and_belongs_to_many relationship

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

提交回复
热议问题