繁体   English   中英

在不使用隐藏字段的情况下将current_user传递给表单(规则4)

[英]Passing current_user to a form without using hidden fields (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

当前,用户可以从瓶子的显示页面上载瓶子的新色板。

这是色板控制器:

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

HAML:

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

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

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

为什么需要通过表单传递current_user 在您的控制器中,如果要将user_id设置为current_user id,只需执行以下操作:

app / models / 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

app / controllers / 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

您不能只为用户使用current_user吗?对于bottle_id,我猜最好是将瓶子放在地址中,因为您正在为瓶子创建样本,所以您的网址可能类似于:

/bottles/<id of bottle>/swatches

你的路线应该是

post "/bottles/:bottle_id/swatches", to: 'swatches#create'

然后,在您的控制器SwatchesController上,您可以

def create
  bottle = Bottle.find(params[:bottle_id])
  swatch = current_user.swatches.create params[:swatch].merge(bottle: bottle)
  if swatch.new_record?
    #something if not saved
  else
    #something if saved
  end
end

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM