【问题标题】:update action not working in rails 4 [closed]更新操作在 Rails 4 中不起作用 [关闭]
【发布时间】:2014-12-16 07:38:49
【问题描述】:

当我更新我的表单时,它会为唯一的字段抛出错误。

在我的模型中

validates :url, presence: true, uniqueness: true, :if => lambda {self.role_id == 2}

以我的形式

= f.text_field :url, :class => 'form-control'

在我的控制器中

def update
respond_to do |format|
  if @user.update(user_params)
    format.html { redirect_to stores_path, notice: 'Store was successfully updated.' }
  else
    format.html { render :edit }
  end
end
end

即使我没有做任何事情,它也会给我错误“此网址已被占用”。请帮忙 提前致谢

【问题讨论】:

  • 您已经有一个与您现在尝试输入的 URL 相同的对象。正如在模型验证中你所说的 url 应该是唯一的,模型会抛出错误。
  • @AlokSwain 你是对的。但我只是在更新对象,甚至没有更改任何字段中的字母表。它如何为自己抛出错误(它是自己的字段值)。
  • 你有没有将@user 定义为 find(... ?
  • @techdreams - 你能插入用户对象和更新期间发送的参数吗?
  • RubyRacer: Yes def set_user @user = User.find(params[:id]) end before_action :set_user, only: [:show, :edit, :update, :destroy] Alok: If I捕获 params 值并插入 update ,我如何在需要的地方应用验证。这可能是安全漏洞

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


【解决方案1】:

我是这样解决的。

def update
respond_to do |format|
  if @user.update(user_params)
    format.html { redirect_to stores_path, notice: 'Store was successfully updated.' }
  else
    incoming_url = User.where("id=? and url=?",@user.id,params[:user][:url])
    if !incoming_url.blank?
      format.html { redirect_to stores_path, notice: 'Store was successfully updated.' }
    end
    format.html { render :edit }
  end
end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-26
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2011-05-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多