Ruby-on-rails 验证失败类必须存在
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38983666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Validation failed Class must exist
提问by Pedro Gabriel Lima
I have been (hours) trouble with associations in Rails. I found a lot of similar problems, but I couldn't apply for my case:
我在 Rails 中遇到了(几个小时)的问题。我发现了很多类似的问题,但是我的case无法申请:
City's class:
市级:
class City < ApplicationRecord
has_many :users
end
User's class:
用户类别:
class User < ApplicationRecord
belongs_to :city
validates :name, presence: true, length: { maximum: 80 }
validates :city_id, presence: true
end
Users Controller:
用户控制器:
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
Users View:
用户视图:
<%= 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
Migrate:
迁移:
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):
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".
好吧,问题是,来自 User 模型的不是 FK 的属性被 User.save 方法接受,而像 citys_id 这样的 FK 属性不是。然后它在浏览器中给我错误消息,说“验证失败的城市必须存在”。
Thanks
谢谢
回答by Igor_Marques
Try the following:
请尝试以下操作:
belongs_to :city, optional: true
According to the new docs:
根据新文档:
4.1.2.11 :optional
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.
4.1.2.11 : 可选
如果将 :optional 选项设置为 true,则不会验证关联对象的存在。默认情况下,此选项设置为 false。
回答by Jeremie
This comes a bit late but this is how to turn off this by defaultin rails 5:
这有点晚了,但这是在 rails 5 中默认关闭它的方法:
config/initializers/new_framework_defaults.rb
配置/初始化程序/new_framework_defaults.rb
Rails.application.config.active_record.belongs_to_required_by_default = false
In case you don't want to add optional: trueto all your belongs_to.
如果您不想添加optional: true到所有belongs_to.
I hope this helps!
我希望这有帮助!
回答by David Kane
You need to add the following to the end of the belongs_to relationship statement:
您需要在belongs_to 关系语句的末尾添加以下内容:
optional: true
It is possible to set this on a global level so that it works in the same way as older versions of rails, but I would recommend taking the time to manually add it to the relationships that really need it as this will cause less pain in the future.
可以在全局级别设置它,以便它以与旧版本 rails 相同的方式工作,但我建议花时间将它手动添加到真正需要它的关系中,因为这会减少未来。
回答by ricks
Rails 5
导轨 5
If you have a belongs_torelationship to :parentthen you have to pass an existing parent object or create a new one then assign to children object.
如果你有一个belongs_to关系,:parent那么你必须传递一个现有的父对象或创建一个新的,然后分配给子对象。
回答by Pedro Gabriel Lima
I found out a solution to the problem "Validation failed: Class must exist" and it's better than use:
我找到了“验证失败:类必须存在”问题的解决方案,它比使用更好:
belongs_to :city, optional: true
4.1.2.11 :optional
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.
4.1.2.11 : 可选
如果将 :optional 选项设置为 true,则不会验证关联对象的存在。默认情况下,此选项设置为 false。
cause you still make a validation in application level. I solve the problem making my own validation in create method and changing user_params method:
因为您仍然在应用程序级别进行验证。我解决了在 create 方法中进行自己验证并更改 user_params 方法的问题:
def create
@city = City.find(params[:city_id])
Rails.logger.debug user_params.inspect
@user = User.new(user_params)
@user.city_id = @city.id
if @user.save!
flash[:success] = "Works!"
redirect_to '/index'
else
render 'new'
end
end
def user_params
params.require(:user).permit(:name)
end
I didn't test this code, but it works in another project mine. I hope it can help others!
我没有测试这段代码,但它适用于我的另一个项目。我希望它能帮助别人!
回答by Purkhalo Alex
belongs_to :city, required: false
回答by Truth Namanya
Rails.application.config.active_record.belongs_to_required_by_default = false
This works because the Rails 5 has true by default to disable you go under Initilizers then click on the New_frame-work and turn the true to false
这是有效的,因为 Rails 5 默认情况下禁用您进入初始化程序,然后单击 New_frame-work 并将 true 变为 false

