验证失败类必须存在 [英] Validation failed Class must exist

查看:18
本文介绍了验证失败类必须存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Rails 中遇到了(几个小时)的关联问题.我发现了很多类似的问题,但是我的case却无法申请:

I have been (hours) trouble with associations in Rails. I found a lot of similar problems, but I couldn't apply for my case:

城市类:

class City < ApplicationRecord
  has_many :users
end

用户类别:

class User < ApplicationRecord
  belongs_to :city

  validates :name, presence: true, length: { maximum: 80 }
  validates :city_id, presence: true
end

用户控制器:

def create
    Rails.logger.debug user_params.inspect
    @user = User.new(user_params)
    if @user.save!
      flash[:success] = "Works!"
      redirect_to '/index'
    else
      render 'new'
    end
 end

def user_params
  params.require(:user).permit(:name, :citys_id)
end

用户视图:

<%= form_for(:user, url: '/user/new') do |f| %>
  <%= render 'shared/error_messages' %>

  <%= f.label :name %>
  <%= f.text_field :name %>

  <%= f.label :citys_id, "City" %>
  <select name="city">
    <% @city.all.each do |t| %>
      <option value="<%= t.id %>"><%= t.city %></option>
    <% end %>
  </select>
end

迁移:

class CreateUser < ActiveRecord::Migration[5.0]
  def change
    create_table :user do |t|
      t.string :name, limit: 80, null: false
      t.belongs_to :citys, null: false
      t.timestamps
  end
end

来自控制台和浏览器的消息:

Message from console and browser:

ActiveRecord::RecordInvalid (Validation failed: City must exist):

好吧,问题是,User.save 方法接受来自 User 模型的非 FK 属性,而 citys_id 等 FK 属性则不是.然后它在浏览器中给我错误消息说验证失败的城市必须存在".

Well, the problem is, the attributes from User's model that aren't FK they are accept by User.save method, and the FK attributes like citys_id are not. Then it gives me error message in browser saying that "Validation failed City must exist".

谢谢

推荐答案

尝试以下操作:

belongs_to :city, optional: true

根据新文档:

4.1.2.11:可选

4.1.2.11 :optional

如果您将 :optional 选项设置为 true,则存在关联的对象将不会被验证.默认设置这个选项为假.

If you set the :optional option to true, then the presence of the associated object won't be validated. By default, this option is set to false.

这篇关于验证失败类必须存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆