将current_user传递给表单而不使用隐藏字段(Rails 4)

Mic*_*lle 1 ruby-on-rails ruby-on-rails-4

目前在我的Rails应用程序中,我有用户,样本和瓶子.

样本属于瓶子和提交它的用户.瓶子不属于用户.

class Swatch < ActiveRecord::Base
  mount_uploader :swatch, SwatchUploader
  belongs_to :user
  belongs_to :bottle
end

class Bottle < ActiveRecord::Base
  has_many :swatches
end

class User < ActiveRecord::Base
  has_many :swatches
end
Run Code Online (Sandbox Code Playgroud)

目前,用户可以从瓶子的展示页面上传瓶子的新样本.

这是样本控制器:

class SwatchesController < ApplicationController
   def create
    @bottle = Bottle.find(params[:bottle_id])
    @user = current_user
    @swatch = @bottle.swatches.create(swatch_params)
    redirect_to bottle_path(@bottle)
  end

  private
    def swatch_params
      params.require(:swatch).permit(:swatch, :user_id, :bottle_id)
    end
end
Run Code Online (Sandbox Code Playgroud)

HAML:

= form_for([@bottle, @bottle.swatches.build]) do |f|
    = f.label :swatch
    = f.file_field :swatch
    = f.submit
Run Code Online (Sandbox Code Playgroud)

使用此设置,除非我将当前用户的ID作为隐藏字段传递,否则表单将不起作用.但我知道这是不好的做法,并希望避免这种情况.

所以我的问题是:如何通过控制器传递bottle_id当前用户和当前用户user_id

CDu*_*Dub 7

你为什么需要current_user通过表格?在您的控制器中,如果要设置user_idcurrent_userid,只需这样做:

应用程序/模型/ swatch.rb

class Swatch < ActiveRecord::Base
  mount_uploader :swatch, SwatchUploader
  belongs_to :user
  belongs_to :bottle

  def set_user!(user)
    self.user_id = user.id

    self.save!
  end
end
Run Code Online (Sandbox Code Playgroud)

应用程序/控制器/ swatches_controller.rb

class SwatchesController < ApplicationController
  def create
    @bottle = Bottle.find(params[:bottle_id])

    @user = current_user

    @swatch = @bottle.swatches.new(swatch_params)
    @swatch.set_user!(current_user)

    redirect_to bottle_path(@bottle)
  end

  private

  def swatch_params
    params.require(:swatch).permit(:swatch, :bottle_id)
  end
end
Run Code Online (Sandbox Code Playgroud)