将属性值添加到rails中的表记录

时间:2015-02-17 07:48:59

标签: ruby-on-rails ruby-on-rails-4

我想在产品#create action时插入user_id。

如何在productController中插入user_id ??

用户只是模特。

这里是 products_controller.rb

  def create

    @user = current_user
    @product = Product.new(product_params, user_id: user_id)

    respond_to do |format|
      if @product.save

        format.html { redirect_to wardrobe_items_path, notice: 'Product was successfully created.' }
        format.json { render :show, status: :created, location: @product }
      else
        format.html { render :new }
        format.json { render json: @product.errors, status: :unprocessable_entity }
      end
    end
  end

产品表

class AddUserIdToProducts < ActiveRecord::Migration
  def change
    add_column :products, :user_id, :string
  end
end

2 个答案:

答案 0 :(得分:0)

这样做

@product = Product.new(product_params)
@product.user_id = current_user.id

答案 1 :(得分:0)

这样做......

def create

    @user = current_user
    @product = Product.new(product_params)
    @product.user_id = current_user.id
    respond_to do |format|
      if @product.save

        format.html { redirect_to wardrobe_items_path, notice: 'Product was successfully created.' }
        format.json { render :show, status: :created, location: @product }
      else
        format.html { render :new }
        format.json { render json: @product.errors, status: :unprocessable_entity }
      end
    end
end