验证失败的类必须存在

问题描述 投票:39回答:7

我在Rails中遇到(数小时)的麻烦。我发现了很多类似的问题,但是我无法申请此案:

城市等级:

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

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

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

好,问题在于,User.save方法不接受用户模型中非FK的属性,而诸如citys_id之类的FK属性则不被接受。然后它在浏览器中显示错误消息,提示“必须存在验证失败的城市”。

谢谢

ruby-on-rails validation associations model-associations belongs-to
7个回答
80
投票

尝试以下操作:

belongs_to :city, optional: true

根据new docs

4.1.2.11:可选

如果将:optional选项设置为true,则存在关联的对象将不会被验证。 默认情况下,此选项已设置为假。


11
投票

这有点晚了,但是这是在Rails 5中如何关闭此默认设置

config / initializers / new_framework_defaults.rb] >>

Rails.application.config.active_record.belongs_to_required_by_default = false

如果您不想将optional: true添加到所有belongs_to中。

我希望这会有所帮助!


4
投票

您需要将以下内容添加到belongs_to关系语句的末尾:


2
投票

我找到了一个解决方案“验证失败:类必须存在”的解决方案,它比使用更好:]

belongs_to :city, optional: true

2
投票

Rails 5


1
投票
belongs_to :city, required: false

0
投票
Rails.application.config.active_record.belongs_to_required_by_default = false
© www.soinside.com 2019 - 2024. All rights reserved.