has_many构建方法,Rails
另一个新手问题。
目标:每种成分可以有零个或多个单位转换。 我想在显示特定成分的页面上创建一个新的单位转换链接。 我不能完全开始工作。
成分模型:
class Ingredient < ActiveRecord::Base belongs_to :unit has_many :unit_conversion end
单位换算模型:
class UnitConversion < ActiveRecord::Base belongs_to :Ingredient end
单位转换控制器(适用于新)
def new @ingredient = Ingredient.all @unit_conversion = @ingredient.unit_conversions.build(params[:unit_conversion]) if @unit_conversion.save then redirect_to ingredient_unit_conversion_url(@ingredient, @comment) else render :action => "new" end end
相关路线:
map.resources :ingredients, :has_many => :unit_conversions
显示成分链接:
这是错误:
NoMethodError in Unit conversionsController#new undefined method `unit_conversions' for # RAILS_ROOT: C:/Users/joan/dh Application Trace | Framework Trace | Full Trace C:/Users/joan/dh/app/controllers/unit_conversions_controller.rb:14:in `new'
救命! 我对这一切都很不满。
用于new
和create
单位转换控制器应该是:
def new @ingredient = Ingredient.find(params[:ingredient_id]) @unit_conversion = @ingredient.unit_conversions.build end def create @ingredient = Ingredient.find(params[:ingredient_id]) @unit_conversion = @ingredient.unit_conversions.build(params[:unit_conversion]) if @unit_conversion.save flash[:notice] = "Successfully created unit conversion." redirect_to ingredient_unit_conversions_url(@ingredient) else render :action => 'new' end end
此外,此截屏video是嵌套资源的一个很好的资源。
has_many :unit_conversion
因为你用它来调用它应该是多元化的
@unit_conversion = @ingredient.unit_conversions.build
你的控制器
def new @ingredient = Ingredient.all
应该叫#new
设置一个新的Ingredient或#find
来获取现有的Ingredient。
@ingredient = Ingredient.new # returns a new Ingredient
要么
@ingredient = Ingredient.find(...) # returns an existing Ingredient
您选择哪一个符合您的要求。
另外,这是一个错字,对吧?
belongs_to :Ingredient
你可能想要小写:ingredient