Ruby on rails 建立关联时未定义的方法
我有两种型号:Ruby on rails 建立关联时未定义的方法,ruby-on-rails,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 :nom
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
你能告诉我怎么了吗?在你的控制器中,你写道:
@warehouse = @aceite.warehouses.build(aceite_params)
这一行是错误的。正如您在模型中定义的那样,acite
属于仓库
。但在上面提到的那一行,你做了相反的事情。您的代码反映了仓库
属于acite
。因此,修订后的守则将是:
您正在尝试建立一个仓库。这是不正确的。
首先,查找特定的仓库(可能您定义了嵌套路由):
如果未定义嵌套管线:
@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
这是因为在
Aceite
实例上没有定义方法warehouses
。明白了!现在似乎可以工作了,我如何在“Aceites”视图中访问仓库名称而不是ID?我现在有aceite.warehouse\u id。但是我希望能够显示名称aceite.warehouse.name获取特定的aceite
对象,如在显示页面中:@aceite=aceite.find(params[:id])
,并在视图中@aceite.warehouse.name
对显示页面有意义,但对索引没有意义?我现在有了@aceites=Aceite.all
,如果我把@Aceite=Aceite.find(params[:id])
放进去,它说没有id就找不到Aceite。
Completed 500 Internal Server Error in 13ms (ActiveRecord: 0.0ms)
NoMethodError (undefined method `warehouses' for #<Aceite:0x00007f1141dfe2c0>
@warehouse = @aceite.warehouses.build(aceite_params)
@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