建立关联时未定义的方法

时间:2018-08-13 03:44:55

标签: ruby-on-rails

我有两个模型,

Aceites belongs_to Warehouse
Warehouse has_many Aceites

这些是我的模特:

class Warehouse < ApplicationRecord
  has_many :aceites
  validates :nombre, presence: true
end

class Aceite < ApplicationRecord
  belongs_to :warehouse
  validates :nombre, presence: true
  validates :tipo, presence: true
  validates :stock, presence: true
  validates :warehouse_id, presence: true
end

Aceites控制器(只会放入关键方法):

class AceitesController < ApplicationController
    def new
        @aceite = Aceite.new
    end

    def create
        @aceite = Aceite.new(aceite_params)
        @warehouse = @aceite.warehouses.build(aceite_params)
        respond_to do |format|
            if @aceite.save
                format.html { redirect_to aceites_url, notice: "Product added!" }
                format.js
            else
                format.js
            end
        end
    end

    private

        def aceite_params
            params.require(:aceite).permit(:nombre, :tipo, :stock, :warehouse_id)
        end
end

表格:

<%= form_for(@aceite, remote: true, :html => { class: 'form-horizontal', role: 'form' }) do |form| %>
  <div class="form-group">
    <%= form.label :nombre, class: 'form-control-label' %>
    <%= form.text_field :nombre, class: 'form-control' %>
  </div>

  <div class="form-group">
    <%= form.label :tipo, class: 'form-control-label' %>
    <%= form.text_field :tipo, class: 'form-control' %>
  </div>

  <div class="form-group">
    <%= form.label :stock, class: 'form-control-label' %>
    <%= form.number_field :stock, class: 'form-control' %>
  </div>

  <div class="form-group">
    <%= form.label :warehouse_id, class: 'form-control-label' %>
    <%= form.collection_select(:warehouse_id, Warehouse.all, :id, :nombre) %>
  </div>

  <%= form.submit @aceite.new_record? ? "Add Product" : "Edit Product", class: "btn btn-primary btn-sm" %>

<% end %>

当我尝试创建与Aceite关联的新Warehouse(一种产品)时,出现以下错误:

Completed 500 Internal Server Error in 13ms (ActiveRecord: 0.0ms)
NoMethodError (undefined method `warehouses' for #<Aceite:0x00007f1141dfe2c0>

你能告诉我出什么问题了吗?

1 个答案:

答案 0 :(得分:0)

在您的控制器中,您写道:

@warehouse = @aceite.warehouses.build(aceite_params)

此行是错误。如您在模型中定义的,Aceite属于Warehouse。但是在提到的那一行中,您做了相反的事情。您的代码反映出Warehouse属于Aceite。因此,修改后的代码将是:

您正在尝试建立一个仓库。哪个不正确。

首先,找到特定的仓库(也许您定义了嵌套路线):

@warehouse = Warehouse.find(params[:warehouse_id])
@aceite = @warehouse.aceites.new(aceite_params)
if @aceite.save
     ----- do something
end

如果您未定义嵌套路线:

@aceite = Aceite.new(aceite_params) # in your aceite_params there is a warehouse_id, so the association will be done by rails
if @aceite.save
     ----- do something
end