另一个新手问题。

目标:每种成分可以具有零个或多个单位转换。我想在显示特定成分的页面上添加一个链接以创建一个新的单位转换。我不能完全正常工作。

成分模型:

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


显示成分链接:

<%= link_to 'Add Unit Conversion', new_ingredient_unit_conversion_path(@ingredient) %>


这是错误:

 NoMethodError in Unit conversionsController#new

undefined method `unit_conversions' for #<Array:0x3fdf920>

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'


救命!我对此感到困惑。

最佳答案

newcreate的单位转换控制器应为:

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


另外,此screencast是嵌套资源的不错的资源。

关于ruby-on-rails - has_many构建方法,Rails,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/1993615/

10-16 23:07