【发布时间】:2016-12-23 08:18:24
【问题描述】:
我在 Rails 中遇到了(几个小时)的关联问题。发现很多类似的问题,但是申请不了我的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
来自控制台和浏览器的消息:
ActiveRecord::RecordInvalid (Validation failed: City must exist):
好吧,问题是,来自 User 模型的非 FK 属性被 User.save 方法接受,而像 citys_id 这样的 FK 属性则不是。然后它在浏览器中给我错误消息说“验证失败的城市必须存在”。
谢谢
【问题讨论】:
标签: ruby-on-rails validation associations model-associations belongs-to