has_many build method, Rails

前端 未结 2 1487
后悔当初
后悔当初 2021-02-19 09:13

Another newbie question.

The goal: each ingredient can have zero or more unit conversions tied to it. I want to put a link to creating a new unit conversion on the page

2条回答
  •  借酒劲吻你
    2021-02-19 09:42

    Unit Conversion Controller for new and create should be:

    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
    

    Also, this screencast is a nice resource for nested resources.

提交回复
热议问题