validation失败类必须存在

我在Rails中遇到了很多关联的问题。 我发现了很多类似的问题,但我不能申请我的案子:

城市class级:

class City < ApplicationRecord has_many :users end 

用户class级:

 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 

用户查看:

        <option value="">   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): 

嗯,问题是,用户模型的属性不是FK,它们是User.save方法接受的,而像citys_id这样的FK属性则不是。 然后它在浏览器中给出了错误消息,说“validation失败的城市必须存在”。

谢谢

请尝试以下方法:

 belongs_to :city, optional: true 

根据新的文档 :

4.1.2.11:可选

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

这有点晚了,但这是默认情况下在rails 5中关闭它的方法

配置/初始化/ new_framework_defaults.rb

 Rails.application.config.active_record.belongs_to_required_by_default = false 

如果您不想为所有belongs_to添加optional: true

我希望这有帮助!

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

 optional: true 

可以在全局级别设置它,以便它与旧版本的rails一样工作,但我建议花时间手动将其添加到真正需要它的关系中,因为这会减少未来。

我发现问题的解决方案“validation失败:类必须存在”,它比使用更好:

 belongs_to :city, optional: true 

4.1.2.11:可选

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

因为你仍然在应用程序级别进行validation。 我解决了在create方法中创建自己的validation并更改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 

我没有测试这段代码,但它可以在另一个项目中使用。 我希望它可以帮助别人!

 belongs_to :city, required: false 

Rails 5

如果你有一个belongs_to关系:parent,那么你必须传递一个现有的父对象或创建一个新对象然后分配给子对象。