ruby on rails - store current_user (devise) in related table? -


i use devise our user management.

models:

class user < activerecord::base   # include default devise modules. others available are:   # :confirmable, :lockable, :timeoutable , :omniauthable   devise :database_authenticatable, :registerable,          :recoverable, :rememberable, :trackable, :validatable   attr_accessible :email, :password, :password_confirmation, :remember_me, :name    has_many :carts     end  class cart < activerecord::base   has_many :line_items, dependent: :destroy   accepts_nested_attributes_for :line_items   belongs_to :user  end 

cart_controller:

def create     @cart = current_user.cart.new(cart_params)      respond_to |format|       if @cart.save         format.html { redirect_to @cart, notice: 'cart created.' }         format.json { render action: 'show', status: :created, location: @cart }       else         format.html { render action: 'new' }         format.json { render json: @cart.errors, status: :unprocessable_entity }       end     end   end  private      def cart_params       params[:cart]     end 

module:

module currentcart   extend activesupport::concern    private      def set_cart        @cart = cart.find(session[:cart_id])     rescue activerecord::recordnotfound       @cart = cart.create       session[:cart_id] = @cart.id      end end 

when cart created (when list item added) want store in user.id in cart table (user_id). thought use current_user method this

  @cart = current_user.cart.new(cart_params) 

the cart created items user_id in cart table remains empty. doing wrong?

thanks..remco

as matt gibson pointed out(and that's how create new cart association):

@cart = current_user.carts.build(cart_params) 

but, think not working expect because of rails 4's strong parameters. might want change this:

private      def cart_params       params[:cart]     end 

to:

private      def cart_params       params.require(:cart).permit(:name, :state) # @ :name, :state use attributes you're getting form cart!     end 

change

def set_cart    @cart = cart.find(session[:cart_id]) rescue activerecord::recordnotfound   @cart = cart.create   session[:cart_id] = @cart.id  end 

to:

def set_cart    @cart = cart.find(session[:cart_id]) rescue activerecord::recordnotfound   @cart = current_user.carts.create   session[:cart_id] = @cart.id # since you're setting id in session use update later! end 

Comments

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

jsf - How to ajax update an item in the footer of a PrimeFaces dataTable? -

django - CSRF verification failed. Request aborted. CSRF cookie not set -