这个问题困扰了我一段时间,我似乎无法找到任何(工作)问题的答案。
所以,基本上问题是当我尝试将表单提交到数据库时,而不是将我输入的数据插入属于嵌套属性(basic_details_set)的字段中,它似乎搜索该行的特定表具有匹配的ID。
这是错误:
ActiveRecord::RecordNotFound in PagesController#create
Couldn't find BasicDetailsSet with ID=1 for Page with ID=1
页面模型:
class Page < ApplicationRecord
belongs_to :dealership, { :optional => false }
has_and_belongs_to_many :admin_users
has_one :basic_details_set
accepts_nested_attributes_for :basic_details_set
end
基本详细信息设置模型:
class BasicDetailsSet < ApplicationRecord
belongs_to :page
end
页面控制器:
class PagesController < ApplicationController
layout 'admin'
before_action :find_dealership
def index
@pages = @dealership.pages.sorted
end
def show
end
def new
@page = Page.new(:dealership_id => @dealership.id)
@page.build_basic_details_set
end
def create
@page = Page.new(page_params)
@page.save
end
def edit
@page = Page.find(params[:id])
end
def update
end
def delete
end
def destroy
end
private
def find_dealership
@dealership = Dealership.find(params[:dealership_id])
end
def page_params
params.require(:page).permit(:id, :permalink, :active, :dealership_id, basic_details_set_attributes: [:id, :price])
end
end
表格部分:
<table>
<tr>
<th>ID:</th>
<td><%= f.text_field(:id) %></td>
</tr>
<tr>
<th>Link:</th>
<td><%= f.text_field(:permalink) %></td>
</tr>
<tr>
<th>Aktiv:</th>
<td><%= f.check_box(:active) %></td>
</tr>
<tr>
<th>Forhandler ID:</th>
<td><%= f.text_field(:dealership_id) %></td>
</tr>
<%= f.fields_for :basic_details_set do |p| %>
<tr>
<th>ID:</th>
<td><%= p.text_field(:id) %></td>
</tr>
<tr>
<th>Pris:</th>
<td><%= p.text_field(:price) %></td>
</tr>
<% end %>
new.html.erb:
<div>
<h2>Ny Side</h2>
<%= form_for(@page, :url => pages_path(:dealership_id => @dealership.id)) do |f| %>
<%= render(:partial => 'form', :locals => {:f => f}) %>
<div><%= f.submit("Opret Side") %></div>
<% end %>
</div>
链接查看所有经销商的页面(内部视图/经销商/索引)
<%= link_to("Vis sider", pages_path(:dealership_id => dealership.id), :class => 'action show') %>
显示上述链接中使用的操作
def show
@dealership = Dealership.find(params[:id])
end
的routes.rb
Rails.application.routes.draw do
root 'dealerships#index'
resources :dealerships do
member do
get :delete
end
end
resources :pages do
member do
get :delete
end
end
end
为什么会发生这种情况以及可能的解决方法?
答案 0 :(得分:0)
好的,所以你的问题出现在表格的这一部分
<%= f.fields_for :basic_details_set do |p| %>
<tr>
<th>ID:</th>
<td><%= p.text_field(:id) %></td>
</tr>
<tr>
<th>Pris:</th>
<td><%= p.text_field(:price) %></td>
</tr>
<% end %>
您似乎正在创建嵌套资源,但您不需要添加id文本字段,因为在创建时,默认情况下将填充ID。
如果你在这里传递一个id,它将尝试更新该ID,目前它不存在,所以只需从表单中删除id字段,一切都会正常工作。