创建嵌套资源的新方法时出错

时间:2017-08-03 16:59:58

标签: ruby nested resources

我有我的资源:

  resources :flows do
    resources :fmodules
  end

fmodules控制器中的新方法:

# /flows/1/fmodules/new
def new
    @flow = Flow.find(params[:flow_id])
    @fmodule = @flow.fmodules.build
end

模特:

class Flow < ApplicationRecord
    has_many :fmodules, dependent: :destroy
    validates :code, presence: true, length: { maximum: 5 }
    validates :name, presence: true
end
class Fmodule < ApplicationRecord
    belongs_to :flow
end

当我尝试/flows/1/fmodules/new时,ruby说unknown attribute 'flow_id' for Fmodule.

我不知道出了什么问题

此外还有Fmodel的迁移

class CreateFmodules < ActiveRecord::Migration[5.1]
  def change
    create_table :fmodules do |t|
      t.string :code
      t.string :name
      t.string :f_code

      t.timestamps
    end
    add_foreign_key :fmodules, :flows, column: :f_code
  end
end

1 个答案:

答案 0 :(得分:0)

因此,问题是您的flow_id表格中没有fmodules。在rails中,按照惯例,外键是从您传递给belongs_to的参数自动推断列名称。这就是为什么rails认为flows表的外键是flow_id并且它引发异常而不找到它的原因。您可以使用foreign_key选项覆盖默认值,如下所示

class Fmodule < ApplicationRecord
    belongs_to :flow, foreign_key: : f_code
end