has_many 构建方法,Rails [英] has_many build method, Rails
本文介绍了has_many 构建方法,Rails的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
另一个新手问题.
目标:每种成分都可以有零个或多个与之相关的单位转换.我想在显示特定成分的页面上放置一个创建新单位转换的链接.我无法让它正常工作.
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 that shows a specific ingredient. I can't quite get it to work.
成分模型:
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'
帮助!我对此很困惑.
推荐答案
new
和 create
的单位转换控制器应该是:
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.
这篇关于has_many 构建方法,Rails的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文