रेल में एसोसिएशन के साथ मुझे (घंटों) परेशानी हो रही है। मैं इसी तरह की समस्याओं का एक बहुत कुछ पाया है, लेकिन मैं अपने मामले के लिए आवेदन नहीं कर सकता:सत्यापन विफल हुआ कक्षा
शहर के वर्ग:
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 नहीं हैं वे User.save विधि द्वारा स्वीकार कर रहे हैं , और fk विशेषताएँ जैसे शहर_आईडी नहीं हैं। फिर यह मुझे ब्राउजर में त्रुटि संदेश देता है कि "सत्यापन विफल शहर मौजूद होना चाहिए"। new docs के अनुसार
belongs_to :city, optional: true
:
धन्यवाद
संभावित डुप्लिकेट [नलबल विदेशी कुंजी जोड़ें] (http://stackoverflow.com/questions/27589399/add-nullable-foreign-key) –