尝试在嵌套资源中创建类别的子类别。我遇到的问题是它似乎不起作用。我得到的是{<#:0x007f8fcde33550>的undefined method
sub_category_path'。
你的意思是? new_category_path swell as
表单的第一个值不能为nil`。
我的控制器方法如下:
SubCategory更新:
@category = @subcategory.category.id
if @subcategory.update(subcategory_params)
flash[:success] = "Subcat name updated"
redirect_to category_sub_category_path(@subcategory)
else
render 'edit'
end
SubCategory new:
@category = Category.find(params[:category_id]) # TODO:subcategory.category.id?
@category_sub = @category.sub_categories.new
#@subcategory = @category.sub_categories.new
SubCategory create:
@subcategory = SubCategory.new(subcategory_params)
if @subcategory.save
flash[:success] = "subcategory created"
redirect_to category_sub_category_path
else
flash[:error] = "subcategory failed"
render 'new'
end
我的私人方法:
private
def set_sub_category
@subcategory = SubCategory.find(params[:id])
end
def subcategory_params
params.require(:sub_category).require(:name, :category_id)
end
end
我没有SubCategories索引,SubCategory的查看基于点击Categories index.html.erb
中的链接,可以在此处看到:
<%@categories.each do |c|%>
<ul class="listing">
<div class="row">
<div class="well col-md-4 col-md-offset-4">
<li class="article-title">
<strong><%= link_to "#{c.name}", category_path(c)%></strong>
<% c.sub_categories.each do |s|%>
<div>
<%=link_to s.name, category_sub_category_path(c,s)%>
</div>
<%end%>
</li>
<li><small>
<!--Pluralise here-->
</small></li>
</div>
</div>
</ul>
<%end%>
然后在我的SubCategory show.html.erb
:
<span class ="badge"><%= link_to "Edit sub category name",
edit_category_sub_category_path([@category, @subcategory])%></span>
在我的SubCategory edit.html.erb
:
<%=form_for([@category, @subcategory], :html => {class: "form-horizontal", role: "form"})do |f|%>
<div class="form-group">
<div class="control-label col-sm-2">
<%= f.label :subcategory%>
</div>
<div class="col-sm-8">
<%= f.text_field :name, class: "form-control", placeholder: "Update Sub Category", autofocus: true%>
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<%=f.submit class: "btn btn-primary btn-lg"%>
</div>
</div>
<%end%>
任何帮助将不胜感激
编辑:
错误 我现在收到此错误
{"utf8"=>"✓", "_method"=>"patch", "authenticity_token"=>"81lwz0NufTqdOni+4wPRO4Vnmeis9f32+sqSNsxTXZY7ufyR8hTvF86KQwdMjcOP2DQJibK66croW48Uhos9+A==", "sub_category"=>{"name"=>"Gold", "category_id"=>"1"}, "commit"=>"Update Sub category", "category_id"=>"1", "id"=>"1"}
因为错误的参数数量(给定2期望1)
def
subcategory_params params.require(:sub_category).require(:name, :category_id)
end
固定:刚拿出第二个.require,不知道为什么我把它放在那里
答案 0 :(得分:2)
正如您在评论中提到的,编辑操作必须像
def edit
@subcategory = SubCategory.find(params[:id])
end
因此值@category
为零导致错误first value of a form cannot be nil
。
将编辑操作设为
def edit
@subcategory = SubCategory.find(params[:id])
@category = @subcategory.category
end
假设你有类别和子类别之间的关系。