Rails编辑表单

huangapple 未分类评论46阅读模式
英文:

Rails Edit Form

问题

当我想进入编辑页面时,我一直在遇到这个错误:“NO ROUTE MATCHES”,但奇怪的是,当我将 **order = @order** 更改为 **@order.listing** 时,一切都正常,但没有信息可供编辑,我已经为这个错误苦恼了一段时间。

**这是我的 Orders 控制器:**
```ruby
    class OrdersController < ApplicationController
      before_action :set_order, only: [:show, :edit, :update, :destroy]
      before_action :authenticate_user!
    
      # GET /orders
      # GET /orders.json
      def index
        @orders = Order.all
      end
    
      # GET /orders/1
      # GET /orders/1.json
      def show
      end
    
      # GET /orders/new
      def new
        @order = Order.new
        @listing = Listing.find(params[:listing_id])
      end
    
      # GET /orders/1/edit
      def edit
      end
    
      # POST /orders
      # POST /orders.json
      def create
        @order = Order.new(order_params)
        @listing = Listing.find(params[:listing_id])
        @seller = @listing.user
    
        @order.listing_id = @listing.id
        @order.buyer_id = current_user.id
        @order.seller_id = @seller.id
    
        respond_to do |format|
          if @order.save
            format.html { redirect_to root_url, notice: 'Pedido creado' }
            format.json { render :show, status: :created, location: @order }
          else
            format.html { render :new }
            format.json { render json: @order.errors, status: :unprocessable_entity }
          end
        end
      end
    
      # PATCH/PUT /orders/1
      # PATCH/PUT /orders/1.json
      def update
        respond_to do |format|
          if @order.update(order_params)
            format.html { redirect_to @order, notice: 'El pedido fue actualizado' }
            format.json { render :show, status: :ok, location: @order }
          else
            format.html { render :edit }
            format.json { render json: @order.errors, status: :unprocessable_entity }
          end
        end
      end
    
      # DELETE /orders/1
      # DELETE /orders/1.json
      def destroy
        @order.destroy
        respond_to do |format|
          format.html { redirect_to orders_url, notice: 'El pedido fue eliminado con exito' }
          format.json { head :no_content }
        end
      end
    
      private
        # Use callbacks to share common setup or constraints between actions.
        def set_order
          @order = Order.find(params[:id])
        end
    
        # Only allow a list of trusted parameters through.
        def order_params
          params.require(:order).permit(:address, :city, :state)
        end
    end

我的编辑页面:

<h1>编辑订单</h1>
<%= render 'form', order: @order %>
<%= link_to '返回', listing_orders_path %>

表单:

<%= form_for(model: [@listing, order], local: true) do |form| %>
  <% if order.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(order.errors.count, "error") %> 阻止保存此订单:</h2>

      <ul>
        <% order.errors.full_messages.each do |message| %>
          <li><%= message %></li>
        <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= form.label :address %>
    <%= form.text_field :address %>
  </div>

  <div class="field">
    <%= form.label :city %>
    <%= form.text_field :city %>
  </div>

  <div class="field">
    <%= form.label :state %>
    <%= form.text_field :state %>
  </div>

  <div class="actions">
    <%= form.submit %>
  </div>
<% end %>

附加信息:

routes.rb:

Rails.application.routes.draw do
  devise_for :users
  resources :listings do
    resources :orders
  end
end

rake routes:

Prefix Verb   URI Pattern   Controller#Action
...
           listing_orders GET    /listings/:listing_id/orders(.:format)          orders#index
                          POST   /listings/:listing_id/orders(.:format)          orders#create
        new_listing_order GET    /listings/:listing_id/orders/new(.:format)      orders#new
       edit_listing_order GET    /listings/:listing_id/orders/:id/edit(.:format) orders#edit
            listing_order GET    /listings/:listing_id/orders/:id(.:format)      orders#show
                          PATCH  /listings/:listing_id/orders/:id(.:format)      orders#update
                          PUT    /listings/:listing_id/orders/:id(.:format)      orders#update
                          DELETE /listings/:listing_id/orders/:id(.:format)      orders#destroy
...

<details>
<summary>英文:</summary>

I keep getting this error when i want to enter the edit page &quot;NO ROUTE MATCHES&quot; ,but the weird thing is that when i change the **order = @order to @order.listing** it goes fine but there is no info to be edited, and i been scratching my head with this error for a while.

**This is my Orders Controller:**
```ruby
    class OrdersController &lt; ApplicationController
      before_action :set_order, only: [:show, :edit, :update, :destroy]
      before_action :authenticate_user!
    
      # GET /orders
      # GET /orders.json
      def index
        @orders = Order.all
      end
    
      # GET /orders/1
      # GET /orders/1.json
      def show
      end
    
      # GET /orders/new
      def new
        @order = Order.new
        @listing = Listing.find(params[:listing_id])
      end
    
      # GET /orders/1/edit
      def edit
      end
    
      # POST /orders
      # POST /orders.json
      def create
        @order = Order.new(order_params)
        @listing = Listing.find(params[:listing_id])
        @seller = @listing.user
    
        @order.listing_id = @listing.id
        @order.buyer_id = current_user.id
        @order.seller_id = @seller.id
    
        respond_to do |format|
          if @order.save
            format.html { redirect_to root_url, notice: &#39;Pedido creado&#39; }
            format.json { render :show, status: :created, location: @order }
          else
            format.html { render :new }
            format.json { render json: @order.errors, status: :unprocessable_entity }
          end
        end
      end
    
      # PATCH/PUT /orders/1
      # PATCH/PUT /orders/1.json
      def update
        respond_to do |format|
          if @order.update(order_params)
            format.html { redirect_to @order, notice: &#39;El pedido fue actualizado&#39; }
            format.json { render :show, status: :ok, location: @order }
          else
            format.html { render :edit }
            format.json { render json: @order.errors, status: :unprocessable_entity }
          end
        end
      end
    
      # DELETE /orders/1
      # DELETE /orders/1.json
      def destroy
        @order.destroy
        respond_to do |format|
          format.html { redirect_to orders_url, notice: &#39;El pedido fue eliminado con exito&#39; }
          format.json { head :no_content }
        end
      end
    
      private
        # Use callbacks to share common setup or constraints between actions.
        def set_order
          @order = Order.find(params[:id])
        end
    
        # Only allow a list of trusted parameters through.
        def order_params
          params.require(:order).permit(:address, :city, :state)
        end
    end

My Edit Page:

&lt;h1&gt;Editing Order&lt;/h1&gt;
&lt;%= render &#39;form&#39;, order: @order %&gt;
&lt;%= link_to &#39;Atras&#39;, listing_orders_path %&gt;

Form:

&lt;%= form_for(model: [@listing, order], local: true) do |form| %&gt;
  &lt;% if order.errors.any? %&gt;
    &lt;div id=&quot;error_explanation&quot;&gt;
      &lt;h2&gt;&lt;%= pluralize(order.errors.count, &quot;error&quot;) %&gt; prohibited this order from being saved:&lt;/h2&gt;

      &lt;ul&gt;
        &lt;% order.errors.full_messages.each do |message| %&gt;
          &lt;li&gt;&lt;%= message %&gt;&lt;/li&gt;
        &lt;% end %&gt;
      &lt;/ul&gt;
    &lt;/div&gt;
  &lt;% end %&gt;

  &lt;div class=&quot;field&quot;&gt;
    &lt;%= form.label :address %&gt;
    &lt;%= form.text_field :address %&gt;
  &lt;/div&gt;

  &lt;div class=&quot;field&quot;&gt;
    &lt;%= form.label :city %&gt;
    &lt;%= form.text_field :city %&gt;
  &lt;/div&gt;

  &lt;div class=&quot;field&quot;&gt;
    &lt;%= form.label :state %&gt;
    &lt;%= form.text_field :state %&gt;
  &lt;/div&gt;

  &lt;div class=&quot;actions&quot;&gt;
    &lt;%= form.submit %&gt;
  &lt;/div&gt;
&lt;% end %&gt;

ADDITIONAL INFO:

Routes.rb:

Rails.application.routes.draw do
  devise_for :users
  resources :listings do
  	resources :orders
  end
end

Rake routes:

Prefix Verb   URI Pattern   Controller#Action
                     new_user_session GET    /users/sign_in(.:format)                                                                 devise/sessions#new
                         user_session POST   /users/sign_in(.:format)                                                                 devise/sessions#create
                 destroy_user_session DELETE /users/sign_out(.:format)                                                                devise/sessions#destroy
                    new_user_password GET    /users/password/new(.:format)                                                            devise/passwords#new
                   edit_user_password GET    /users/password/edit(.:format)                                                           devise/passwords#edit
                        user_password PATCH  /users/password(.:format)                                                                devise/passwords#update
                                      PUT    /users/password(.:format)                                                                devise/passwords#update
                                      POST   /users/password(.:format)                                                                devise/passwords#create
             cancel_user_registration GET    /users/cancel(.:format)                                                                  devise/registrations#cancel
                new_user_registration GET    /users/sign_up(.:format)                                                                 devise/registrations#new
               edit_user_registration GET    /users/edit(.:format)                                                                    devise/registrations#edit
                    user_registration PATCH  /users(.:format)                                                                         devise/registrations#update
                                      PUT    /users(.:format)                                                                         devise/registrations#update
                                      DELETE /users(.:format)                                                                         devise/registrations#destroy
                                      POST   /users(.:format)                                                                         devise/registrations#create
                       listing_orders GET    /listings/:listing_id/orders(.:format)                                                   orders#index
                                      POST   /listings/:listing_id/orders(.:format)                                                   orders#create
                    new_listing_order GET    /listings/:listing_id/orders/new(.:format)                                               orders#new
                   edit_listing_order GET    /listings/:listing_id/orders/:id/edit(.:format)                                          orders#edit
                        listing_order GET    /listings/:listing_id/orders/:id(.:format)                                               orders#show
                                      PATCH  /listings/:listing_id/orders/:id(.:format)                                               orders#update
                                      PUT    /listings/:listing_id/orders/:id(.:format)                                               orders#update
                                      DELETE /listings/:listing_id/orders/:id(.:format)                                               orders#destroy
                             listings GET    /listings(.:format)                                                                      listings#index
                                      POST   /listings(.:format)                                                                      listings#create
                          new_listing GET    /listings/new(.:format)                                                                  listings#new
                         edit_listing GET    /listings/:id/edit(.:format)                                                             listings#edit
                              listing GET    /listings/:id(.:format)                                                                  listings#show
                                      PATCH  /listings/:id(.:format)                                                                  listings#update
                                      PUT    /listings/:id(.:format)                                                                  listings#update
                                      DELETE /listings/:id(.:format)                                                                  listings#destroy
                          pages_about GET    /pages/about(.:format)                                                                   pages#about
                        pages_contact GET    /pages/contact(.:format)                                                                 pages#contact
                               seller GET    /seller(.:format)                                                                        listings#seller
                                 root GET    /                                                                                        listings#index
        rails_postmark_inbound_emails POST   /rails/action_mailbox/postmark/inbound_emails(.:format)                                  action_mailbox/ingresses/postmark/inbound_emails#create
           rails_relay_inbound_emails POST   /rails/action_mailbox/relay/inbound_emails(.:format)                                     action_mailbox/ingresses/relay/inbound_emails#create
        rails_sendgrid_inbound_emails POST   /rails/action_mailbox/sendgrid/inbound_emails(.:format)                                  action_mailbox/ingresses/sendgrid/inbound_emails#create
  rails_mandrill_inbound_health_check GET    /rails/action_mailbox/mandrill/inbound_emails(.:format)                                  action_mailbox/ingresses/mandrill/inbound_emails#health_check
        rails_mandrill_inbound_emails POST   /rails/action_mailbox/mandrill/inbound_emails(.:format)                                  action_mailbox/ingresses/mandrill/inbound_emails#create
         rails_mailgun_inbound_emails POST   /rails/action_mailbox/mailgun/inbound_emails/mime(.:format)                              action_mailbox/ingresses/mailgun/inbound_emails#create
       rails_conductor_inbound_emails GET    /rails/conductor/action_mailbox/inbound_emails(.:format)                                 rails/conductor/action_mailbox/inbound_emails#index
                                      POST   /rails/conductor/action_mailbox/inbound_emails(.:format)                                 rails/conductor/action_mailbox/inbound_emails#create
    new_rails_conductor_inbound_email GET    /rails/conductor/action_mailbox/inbound_emails/new(.:format)                             rails/conductor/action_mailbox/inbound_emails#new
   edit_rails_conductor_inbound_email GET    /rails/conductor/action_mailbox/inbound_emails/:id/edit(.:format)                        rails/conductor/action_mailbox/inbound_emails#edit
        rails_conductor_inbound_email GET    /rails/conductor/action_mailbox/inbound_emails/:id(.:format)                             rails/conductor/action_mailbox/inbound_emails#show
                                      PATCH  /rails/conductor/action_mailbox/inbound_emails/:id(.:format)                             rails/conductor/action_mailbox/inbound_emails#update
                                      PUT    /rails/conductor/action_mailbox/inbound_emails/:id(.:format)                             rails/conductor/action_mailbox/inbound_emails#update
                                      DELETE /rails/conductor/action_mailbox/inbound_emails/:id(.:format)                             rails/conductor/action_mailbox/inbound_emails#destroy
rails_conductor_inbound_email_reroute POST   /rails/conductor/action_mailbox/:inbound_email_id/reroute(.:format)                      rails/conductor/action_mailbox/reroutes#create
                   rails_service_blob GET    /rails/active_storage/blobs/:signed_id/*filename(.:format)                               active_storage/blobs#show
            rails_blob_representation GET    /rails/active_storage/representations/:signed_blob_id/:variation_key/*filename(.:format) active_storage/representations#show
                   rails_disk_service GET    /rails/active_storage/disk/:encoded_key/*filename(.:format)                              active_storage/disk#show
            update_rails_disk_service PUT    /rails/active_storage/disk/:encoded_token(.:format)                                      active_storage/disk#update
                 rails_direct_uploads POST   /rails/active_storage/direct_uploads(.:format)                                           active_storage/direct_uploads#create

答案1

得分: 0

你已将 orders 设置为 listings 下的嵌套资源:

resources :listings do
  resources :orders
end

这意味着 - 正如从你的路由输出中可以看出的那样 - 编辑订单的 URL 路径为:

/listings/:listing_id/orders/:id/edit

我认为你没有包含链接到编辑页面的代码,但我猜你可能在使用 Rails 生成的 URL 辅助方法,edit_listing_order_path,它需要两个参数:listing_id 和订单 ID。如果你检查那个链接,我的猜测是你没有同时指定这两个 ID。我之所以这么说,是因为如果你看一下编辑页面上的 link_to

<%= link_to 'Atras', listing_orders_path %>

它缺少了适当的 listing 记录的 ID:

<%= link_to 'Atras', listing_orders_path(@listing) %>

我怀疑你需要检查所有的订单路径,以确保你也在指定父级 listing。

你可能还需要在你的 OrdersController 中加载 listing 实例:

def set_order
  @order = Order.find(params[:id])
  @listing = @order.listing    # 或者从参数中获取:Listing.find(params([:listing_id])
end
英文:

You have orders set up as a nested resource under listings:

resources :listings do
  resources :orders
end

That means -- as you can see from your routes output -- that the URL path for editing an order is:

/listings/:listing_id/orders/:id/edit

I don't think you included the code for the link to the edit page, but my guess is you are using the Rails-generated URL helper, edit_listing_order_path, which takes two parameters: a listing_id and an order ID. If you check that link my guess is you aren't specifying both IDs. The reason I say that is that if you look at the link_to on the edit page:

&lt;%= link_to &#39;Atras&#39;, listing_orders_path %&gt;

It is missing the ID of the appropriate listing record:

&lt;%= link_to &#39;Atras&#39;, listing_orders_path(@listing) %&gt;

I suspect you need to check all the orders paths to ensure you are also specifying the parent listing.

The other thing you likely need to do is load the listing instance in your OrdersController:

def set_order
  @order = Order.find(params[:id])
  @listing = @order.listing    # or from parameters: Listing.find(params([:listing_id])
end

huangapple
  • 本文由 发表于 2020年7月24日 07:37:53
  • 转载请务必保留本文链接:https://java.coder-hub.com/63064669.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定