我在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):

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

谢谢

推荐答案

try 以下方法:

belongs_to :city, optional: true

根据new docs人的说法:

4.1.2.11:可选

如果将:optional选项设置为true,则

Ruby-on-rails相关问答推荐

通过激励控制器正确更新Turbo帧信源

在Ruby on rails中,重复访问ActiveRecordModel返回相同的对象:预期行为还是错误?

为什么这个rails Collection_select不呈现关联属性?

Heroku、Selenium、Chome和Chromedriver的复杂问题(抱歉,无法简单描述,请阅读详细信息)

如何为 I18n 设置 raise_on_missing_translations

当我必须更改 rspec 中的方法时,如何检测时间?

如何在 Rails 中使用延迟作业(job)取消预定作业(job)?

rails select标签,预先 Select 了多个值

在 JS 模块中使用 Rails-UJS(带有 webpacker 的 Rails 6)

如何配置设计以使用自定义邮箱布局?

判断 DateTime 值是今天、明天还是以后

fields_for 表单构建器对象为零

如何在 Linux 上使用 Ruby 2.0 改进独角兽进程之间的内存共享

在 Epoch 中将 Ruby 时间戳转换为秒数并返回

在 Rails 中将表格行变成链接

rails 方法获取模型的关联名称

可能在rails中有多态has_one关系?

测试:如何在不损失速度的情况下专注于行为而不是执行?

Ruby/Rails CSV 解析,UTF-8 中的无效字节序列

为什么 Mac OS X 带有 ruby​​/rails?