【问题标题】:Undefined method `update' for Array数组的未定义方法“更新”
【发布时间】:2014-03-26 00:09:25
【问题描述】:

我正在尝试让 Wicked Wizard gem 在我的 Rails 应用程序上运行。一旦用户注册了应用程序(使用 Devise),他们就会被重定向到这个表单:

income.html.erb

<%= form_for @finance, url: wizard_path, :method => :put do |f|  %>
  <div class="field">
    What <strong>year</strong> were you born?<br>
    <%= f.number_field :age %>
  </div>
  <div class="field">
    What's your <strong>zip code</strong>?<br>
    <%= f.number_field :zip %>
  </div>
  <%= f.submit %>
<% end %>

我生成了一个名为finances_welcome_controller.rb 的控制器来处理wizard_path

class FinancesWelcomeController < ApplicationController
  before_filter :authenticate_user!
  include Wicked::Wizard
  steps :income, :expenses
  def show
    @finance = Finance.find_all_by_user_id current_user[:id] || @finance =     current_user.finances.build(finance_params)
    render_wizard
  end
  def update
    @finance = Finance.find_all_by_user_id current_user[:id]
    @finance.update(params[:finance])
    render_wizard @finance
  end

当我单击submit 按钮时,我收到此错误:

NoMethodError in FinancesWelcomeController#update
undefined method `update' for #<Array:0x00000104c6ff48>
Extracted source (around line #14):
    def update
        @finance = Finance.find_all_by_user_id current_user[:id]
        **@finance.update(params[:finance])**
        render_wizard @finance
    end

不确定为什么没有定义更新方法,因为这与我的资源模型使用的语法相同。 Wicked Wizard gem 在this app 上成功实现。

【问题讨论】:

    标签: ruby-on-rails ruby devise wicked-gem


    【解决方案1】:

    find_all_by 开头的方法将返回一个活动记录实例数组...而不仅仅是一个。 update 仅适用于单个实例。

    所以,要么您想遍历数组中的所有实例...使用 each - 或者您只想使用 find_by 而不是 find_all_by 获取第一个实例

    如果通过 id 查找...我建议将其更改为 find_by 所以:

    @finance = Finance.find_by_user_id current_user[:id]
    @finance.update_attributes(params[:finance])
    

    【讨论】:

    • 感谢您的回复 - 这似乎修复了表单提交错误,但不幸的是数据实际上并未保存。我有我的用户与财务相关联,当我点击我的 _form 来编辑财务时,数据并未使用向导提交的内容进行更新。
    • @beaconhill - 试试update_attributes。或者理想情况下@finance.assign_attributes(params[:finance]); finance.save!`
    • 当我返回向导页面(/finance_welcome/income 包含表单的一部分)时它会节省,但当我在实际财务编辑页面(/finance/6/edit)上时不会
    • 您需要提供更多代码/信息供我们查看。您的表单是否在控制器中调用更新操作>? params[:finance] 有哪些参数?这是你所期望的吗?等
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-07-02
    • 2018-06-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多