gpt4 book ai didi

ruby-on-rails - Ruby on Rails 嵌套资源未定义的方法路径

转载 作者:行者123 更新时间:2023-12-04 17:52:38 25 4
gpt4 key购买 nike

我在/config/routes.rb 中定义了嵌套资源

  resources :goals do
resources :goal_entries
end

目标模型:
class Goal < ActiveRecord::Base
attr_accessible :code, :description, :from_date, :to_date
validates_uniqueness_of :code
validates_presence_of :code
has_many :goal_entries, :primary_key => "code", :foreign_key => "goal_code"
accepts_nested_attributes_for :goal_entries
end

对于 GoalEntry :
class GoalEntry < ActiveRecord::Base
attr_accessible :code, :goal_code,
:general_increase_percentage, :general_net_sales,
belongs_to :goal, :primary_key => "code", :foreign_key => "goal_code"
validates_presence_of :code
validates_presence_of :goal_code
validates_uniqueness_of :code , :scope => :goal_code
#validates_numericality_of :general_net_sales

为 Goal 父级创建/编辑 GoalEntry 的 View 如下所示:
<%= form_for([@goal, @goal_entry]) do |f| %>
<% if @goal_entry.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@goal_entry.errors.count, "error") %>
prohibited this goal_entry from being saved:
</h2>
<ul>
<% @goal_entry.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.hidden_field :goal_code, :required => true%>
</div>
<div class="field">
<%= f.label :code %>
<%= f.number_field :code, :required => true %>
</div>
...

目标条目 Controller 中的更新方法:
  def update
@goal_entry = GoalEntry.find(params[:id])

respond_to do |format|
if @goal_entry.update_attributes(params[:goal_entry])
format.html { redirect_to edit_goal_path(@goal_entry.goal), notice: 'Goal entry was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: @goal_entry.errors, status: :unprocessable_entity }
end
end
end

输入有效的目标条目工作正常。但如果有验证错误消息,我会收到以下消息:
    **NoMethodError in Goal_entries#update**
ActionView::Template::Error (undefined method `goal_entry_path' for #<#<Class:0x007fce30a0c160>:0x00000004199570>):
1: <%= form_for([@goal, @goal_entry]) do |f| %>
2: <% if @goal_entry.errors.any? %>
3: <div id="error_explanation">
4: <h2><%= pluralize(@goal_entry.errors.count, "error") %>
app/views/goal_entries/_form.html.erb:1:in `_app_views_goal_entries__form_html_erb__827873423371803667_70261777948540'
app/views/goal_entries/edit.html.erb:3:in `_app_views_goal_entries_edit_html_erb__779650500016633360_70261777920720'
app/controllers/goal_entries_controller.rb:77:in `block (2 levels) in update'
app/controllers/goal_entries_controller.rb:72:in `update'
etc...
<% if @goal_entry.errors.any? %>有什么问题吗?
如果有人对此有解决方案,我将不胜感激。谢谢

最佳答案

您的 form_for 正在从 [@goal, @goal_entry] 生成其路由但您尚未在更新操作中定义 @goal。

尝试添加 @goal = Goal.find(params[:goal_id])到您的更新方法。

关于ruby-on-rails - Ruby on Rails 嵌套资源未定义的方法路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13727414/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com