尝试在rails中创建关联模型的表单,但form_for给出错误";实体#new ";
为nil定义方法' entities':NilClass"模型代码<!--Schema model -->
class Schema < ApplicationRecord
has_many :entities, dependent: :destroy
validates :name, presence: true, uniqueness: true
validates :schemaId, presence: true, uniqueness: true
end
<!--Entity Model -->
class Entity < ApplicationRecord
belongs_to :schema
end
<!-- Entity Controller -->
class EntitiesController < ApplicationController
def index
@schema = Schema.find_by(:id => params[:id])
@entities = @schema.entities
end
def new
@schema = Schema.find_by(:id => params[:id])
@entity = Entity.new
end
def create
@schema = Schema.find_by(:id => params[:id])
@entity = @schema.entities.new(entity_params)
@entity.save!
end
private
def entity_params
params.require(:entity).permit(:clientId, :name, :description, :mnemonic, :schema_id)
结束
结束<!-- Entity_new_form-->
<%= form_for [@schema, @schema.entities.build] do |f| %>
<p>
<%= f.label :clientId %><br/>
<%= f.text_field :clientId %>
</p>
<p>
<%= f.label :name %><br/>
<%= f.text_area :name %>
</p>
<p>
<%= f.label :description %><br/>
<%= f.text_area :description %>
</p>
<p>
<%= f.label :mnemonic %><br/>
<%= f.text_area :mnemonic %>
</p>
<p>
<%= f.submit 'Submit' %>
</p>
<% end %>
如果实体与Schema相关联,就会出现错误。我必须从用户那里输入新的实体,但是这个表单给了我错误。
rails控制台工作正常:
Loading development environment (Rails 7.0.3)
irb(main):001:0> en = Entity.new(clientId:"1",name:"Allergy",description:"Infected By",mnemonic:"Allergy",schema_id:14)
(10.1ms) SELECT sqlite_version(*)
=>
#<Entity:0x000055f1e5e55290
...
irb(main):002:0> en.save
TRANSACTION (0.1ms) begin transaction
Schema Load (0.9ms) SELECT "schemas".* FROM "schemas" WHERE "schemas"."id" = ? LIMIT ? [["id", 14], ["LIMIT", 1]]
Entity Create (66.3ms) INSERT INTO "entities" ("clientId", "name", "description", "mnemonic", "schema_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?) [["clientId", "1"], ["name", "Allergy"], ["description", "Infected By"], ["mnemonic", "Allergy"], ["schema_id", 14], ["created_at", "2022-06-12 06:15:41.888670"], ["updated_at", "2022-06-12 06:15:41.888670"]]
TRANSACTION (21.9ms) commit transaction
=> true
对于给定的params[:id]
,似乎没有Schema
。因此,@schema.entities
与nil.entities
相同。
在这种情况下,你可以使用Schema.find(params[:id])
或Schema.find_by!(id: params[:id])
(注意!
)来清除错误。