【问题标题】:Nested controller Resources, how to do update and destroy?嵌套控制器资源,如何更新和销毁?
【发布时间】:2014-09-09 19:35:04
【问题描述】:

按照教程帮助我在控制器中创建实例。换句话说,事务是在信封控制器上创建的。就像博客文章中的 cmets。

一切正常,但我现在不知道如何编辑交易或销毁交易。我所需要的只是找到如何编辑现有的东西。让我向您展示我目前所拥有的:

在views/envelopes/edit中(表单代码是从您可以创建新交易的地方复制的)

 <% @envelope.transactions.each do |transaction|%>
   <%= form_for [@envelope, @envelope.transactions.build] do |f| %> <!--??? NEED EDIT INSTEAD OF BUILD ???-->
     <%= f.text_field :name, "value" => transaction.name %>
     <%= f.text_field :cash, "value" => transaction.cash %>
     <%= f.submit "Submit" %> 
   <% end %>
   <%= link_to "Remove", root_path %>  <!--??? WANT TO REMOVE TRANSACTION ???-->
 <% end %>

在 routes.rb 中

  resources :envelopes do 
    resources :transactions
  end

在事务控制器中

class TransactionsController < ApplicationController
  def create
    @envelope = Envelope.find(params[:envelope_id])
    @transaction = @envelope.transactions.build(transaction_params)#(params[:transaction])
    @transaction.save

    @envelope.update_attributes :cash => @envelope.cash - @transaction.cash

    redirect_to edit_envelope_path(@envelope)
  end

  def destroy
    # ???
  end

  def update
    # ???
  end

  def transaction_params
    params.require(:transaction).permit(:cash, :name, :envelope_id)
  end
end

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 nested-resources


    【解决方案1】:
      def update
        @transaction = @envelope.transactions.find(params[:id])
        if @transaction.update(transaction_params)
          redirect to @envelope, notice: 'Transaction was successfully updated'
        else
          redirect_to @envelope, notice: 'Transaction was not updated'
        end
      end
    
      def destroy
        @transaction.destroy
        redirect_to @envelope, notice: 'Text here'
      end
    

    【讨论】:

    • 谢谢安德烈!这看起来很神奇,我想尝试一下,但我仍然不确定如何从 form_for 和 link_to 调用这些操作
    • 我认为以下方法会起作用:link_to 'Destroy transaction', envelope_transaction_path(@envelope, transaction), method: 'delete'
    • 大部分情况下确实有效。一旦它确实在事务控制器中调用了该操作,它就会为 nil:nilclass 提供未定义的方法“销毁”。所以我认为事务对象或实例可能不会到达那里。我会继续尝试一些东西,谢谢你的帮助!
    • 好的,做 link_to '销毁交易',envelope_transaction_path(@envelope, @transaction),方法:'delete
    • 我可以在错误页面上看到 id 和信封_id 被传递给控制器​​,而不是对象,所以我在销毁的其余部分之前添加了这些行:' {at}transaction = Transaction.find (params[:id]) {at}envelope = Envelope.find_by_id(params[:envelope_id])' 但是我仍然不知道在 form_for 中调用什么来代替信封.transaction.build。谢谢你的帮助!
    猜你喜欢
    • 2021-06-01
    • 2017-12-18
    • 1970-01-01
    • 2012-03-17
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 2015-07-29
    • 1970-01-01
    相关资源
    最近更新 更多