嵌套资源。 Create方法中的ActiveRecord :: RecordNotFound

时间:2018-07-08 06:36:09

标签: ruby-on-rails

这是我的route.rb文件:

Rails.application.routes.draw do
 resources :invoices
 devise_for :users

 root to: 'pages#home'

  resources :users do
   resources :properties do
   resources :invoices
   end
  end
 end

尽管在创建新属性时我的Properties控制器中的Create方法没有问题:

class PropertiesController < ApplicationController
 before_action :authenticate_user!

 def index
  @properties = Property.all
 end

 def new
  @user =  current_user
  @property = @user.properties.build
 end

 def create
  @user =  current_user
  @property = @user.properties.create(property_params)
  @property.user_id = current_user.id
  if @property.save
   flash[:success] = "Nouveau Bien créé!"
  redirect_to user_properties_path
   else
    render 'static_pages/home'
   end
 end

从“属性控制器”创建发票时,这完全不同:

 class InvoicesController < ApplicationController
  def index
   @invoices = Invoice.all.order('created_at DESC')
  end

  def new
   @property = Property.find(params[:property_id])
   @invoice = @property.invoices.build
  end

  def create
   @property = Property.find(params[:property_id])
   @invoice = @property.invoices.create(invoice_params)
    if @invoice.save
      redirect_to @invoices
    else
      render 'new'
    end
  end

   private

   def invoice_params
    params.require(:invoice).permit(:content)
   end
  end

这是表单视图:

   <%= simple_form_for(@invoice) do |f| %>
     <div class="form-inputs">
     <%= f.input :content %>
   </div>

   <div class="form-actions">
   <%= f.button :submit %>
   </div>
  <% end %>

Rails服务器不断涌出:

“ InvoicesController#create中的ActiveRecord :: RecordNotFound 没有ID找不到财产

为什么可以在New方法中而不是在Create方法中使用(params [:property_id])?

1 个答案:

答案 0 :(得分:0)

我想您需要通过{strong>用户,属性的表单,因为invoice具有嵌套路由。

应该是<%= simple_form_for [current_user, @property, @invoice] do |f| %>