При использовании неглубоких маршрутов , разные маршруты требуют разных аргументов form_for

Здесь я использую простую форму, но это проблема и с обычными формами Rails. При использовании неглубоких маршрутов form_for нужны разные аргументы в зависимости от того, в каком контексте он используется.

Пример: для редактирования (http://localhost:3000/notes/2/edit) _form.html.erb должен иметь simple_form_for(@note). Но для создания новой заметки (http://localhost:3000/customers/2/notes/new) _form.html.erb требуется simple_form_for([@customer, @note]).Если какой-либо из них получит неправильные аргументы, я получу ошибку «Метод не найден».

Как с этим справиться?

  • Я мог бы сделать две отдельные формы, но это выглядит беспорядочно.
  • Мне нужно установить @customer для обратной ссылки, но я мог бы использовать другую переменную в форме (скажем, @customer_form) и просто не устанавливать ее в методах редактирования и обновления, но это непоследовательно и немного сбивает с толку, поскольку Мне пришлось бы установить как @customer_form, так и @customer в новом методе.
  • Я мог бы сделать то, что сделал этот парень, и разбить форму на несколько файлов. Пока это выглядит как лучший вариант, но мне он не очень нравится, так как вы не можете просто открыть _form.html.erb и посмотреть, что происходит.

Это мои единственные варианты?

Ниже приведен пример:

config/routes.rb

Billing::Application.routes.draw do
  resources :customers, :shallow => true do
    resources :notes
  end
end

rake route | grep note

    customer_notes GET    /customers/:customer_id/notes(.:format)         notes#index
                   POST   /customers/:customer_id/notes(.:format)         notes#create
 new_customer_note GET    /customers/:customer_id/notes/new(.:format)     notes#new
         edit_note GET    /notes/:id/edit(.:format)                       notes#edit
              note GET    /notes/:id(.:format)                            notes#show
                   PUT    /notes/:id(.:format)                            notes#update
                   DELETE /notes/:id(.:format)                            notes#destroy

app/views/notes/_form.html.erb

#                      v----------------------------- Right here
<%= simple_form_for (@note), html: { class: 'form-vertical'} do |f| %>
  <%= f.input :content %>

  <%= f.button :submit %>
<% end -%>

app/views/notes/new.html.erb

New note

<%= render 'form' %> <%= link_to 'Back', customer_path(@customer) %>

app/views/notes/edit.html.erb

Editing note

<%= render 'form' %> <%= link_to 'Show', @note %> <%= link_to 'Back', customer_path(@customer) %>

app/controllers /notes_controller.rb

class NotesController < ApplicationController

def show
  @note = Note.find(params[:id])
  @customer = Customer.find(@note.customer_id) 

  respond_to do |format|
    format.html
    format.json {render json: @note }
  end
end

  # GET /notes/new
  # GET /notes/new.json
  def new
    @note = Note.new
    @customer = Customer.find(params[:customer_id])

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @note }
    end
  end

  # GET /notes/1/edit
  def edit
    @note = Note.find(params[:id])
    @customer = Customer.find(@note.customer_id)
  end

  # POST /notes
  # POST /notes.json
  def create
    @customer = Customer.find(params[:customer_id])
    @note = @customer.notes.build(params[:note])

    respond_to do |format|
      if @note.save
        format.html { redirect_to @customer, notice: 'Note was successfully created.' }
        format.json { render json: @note, status: :created, location: @note }
      else
        format.html { render action: "new" }
        format.json { render json: @note.errors, status: :unprocessable_entity }
      end
    end
  end

  # PUT /notes/1
  # PUT /notes/1.json
  def update
    @note = Note.find(params[:id])
    @customer = Customer.find(@note.customer_id)

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

  # DELETE /notes/1
  # DELETE /notes/1.json
  def destroy
    @note = Note.find(params[:id])
    @note.destroy

    respond_to do |format|
      format.html { redirect_to :back }
      format.json { head :no_content }
    end
  end
end

42
задан James 30 March 2012 в 15:13
поделиться