Работа с has_one и единственным ресурсом с вложенным ресурсом

У меня есть модель пользователя, в которой есть_один престатист и есть_один работодатель. Ранее в stackoverflow кто-то посоветовал мне объявлять единичные ресурсы, например:

resources :users do
resource: employeur
resource: prestataire
end

Вместо:

resources :users do
resources: employeurs
resources: prestataires
end

Благодаря рельсам мне не пришлось унифицировать все мои контроллеры и файлы имен представлений. Тем не менее, когда я создаю пользователя и меня перенаправляют на форму работодателя, я получаю неопределенный метод `user_employeurs_path', что правильно, поскольку у меня есть только user_employeur_path. Но я не просил множественное число в своем пользовательском контроллере. Rails указывает, что эта ошибка NoMethodError возникает в первой строке моей формы работодателя ‹%= form_for [@user, @employeur] do |f| %>, где происходит перенаправление при сохранении пользователя.

class UsersController < ApplicationController

#TODO index user doit être suprimé quand inutile pour dev
  def index
    @users = User.all
  end

  def show
    @user = User.find(params[:id])
  end

  def new
    @user = User.new
  end

  # GET /users/1/edit
  def edit
    @user = User.find(params[:id])
  end

  # POST /users
  # POST /users.json
  def create
    @user = User.new(user_params)

    respond_to do |format|
      if @user.save
        if params[:commit] == 'Prestataire'
        format.html { redirect_to new_user_prestataire_path(user_id: @user), notice: "Renseignez vos informations d'employeur" }
        format.json { render action: 'show', status: :created, location: @user }
        else 
        format.html { redirect_to new_user_employeur_path(user_id: @user), notice: "Renseignez vos informations de prestataire" }
        format.json { render action: 'show', status: :created, location: @user }
        end
      else
        format.html { render action: 'new' }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /users/1
  # PATCH/PUT /users/1.json
  def update
    @user = User.find(params[:id])
    respond_to do |format|
      if @user.update(user_params)
        if params[:commit] == 'Prestataire'
        format.html { redirect_to new_user_prestataire_path(user_id: @user), notice: 'User was successfully updated.' }
        format.json { head :no_content }
        else 
        format.html { redirect_to new_user_employeur_path(user_id: @user), notice: "User was successfully updated." }
        format.json { head :no_content }
        end
      else
        format.html { render action: 'edit' }
        format.json { render json: @user.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /users/1
  # DELETE /users/1.json
  def destroy
    @user = User.find(params[:id])
    @user.destroy
    respond_to do |format|
      format.html { redirect_to users_url }
      format.json { head :no_content }
    end
  end

private
  def user_params
    params.require(:user).permit(:email, :password, :password_confirmation, :surname, :forename, :civility, :phone)
  end

end

Форма пользователя:

<%= form_for(@user) do |f| %>
  <% if @user.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@user.errors.count, "error") %> prohibited this user from being saved:</h2>

      <ul>
      <% @user.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :civility, 'Titre de civilité: ' %><br>
    <%= f.text_field :civility %>
  </div>

  <div class="field">
    <%= f.label :forename, 'Prénom: ' %><br>
    <%= f.text_field :forename %>
  </div>
  <div class="field">
    <%= f.label :surname, 'Nom de famille: ' %><br>
    <%= f.text_field :surname %>
  </div>
  <div class="field">
    <%= f.label :email, 'Email: ' %><br>
    <%= f.text_field :email %>
  </div>
  <div class="field">
    <%= f.label :password, 'Mot de passe: ' %><br>
    <%= f.password_field :password, size: 40 %>
  </div>
  <div class="field">
    <%= f.label :password_confirmation, 'Confirmation de mot de passe: ' %><br>
    <%= f.password_field :password_confirmation, size: 40 %>
  </div>
  <div class="field">
    <%= f.label :phone, 'Numéro de téléphone: ' %><br>
    <%= f.text_field :phone %>
  </div>
  <div class="actions">
    <%= f.submit "Employeur" %>
    <%= f.submit "Prestataire" %>
  </div>
<% end %>

Форма работодателя:

<%= form_for [@user, @employeur] do |f| %>
  <% if @employeur.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@employeur.errors.count, "error") %> prohibited this employeur from being saved:</h2>

      <ul>
      <% @employeur.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :siren, 'Siren: ' %><br>
    <%= f.text_field :siren %>
  </div>
  <div class="field">
    <%= f.label :societe, 'Société: ' %><br>
    <%= f.text_field :societe %>
  </div>
  <div class="field">
    <%= f.label :code_postal, 'Code Postal: ' %><br>
    <%= f.text_field :code_postal %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

Что касается моего документа new.html для работодателя:

<h1>New employeur</h1>
<%= render 'form' %>

person Francky    schedule 27.05.2014    source источник


Ответы (2)


Я считаю, что вы можете использовать параметр url в этом случае. Попробуйте что-то вроде:

<%= form_for [@user, @employeur], url: user_employeur_path do |f| %>
   ...
person Marek Takac    schedule 27.05.2014
comment
Вау, впечатляет! Я не ожидал этого, но это сработало! Большое спасибо. - person Francky; 28.05.2014

Вот что происходит:

когда вы передадите <%= form_for [@user, @employeur] do |f| %>, Rails соединит объекты (@user и @employeur) в том порядке, в котором вы передали, а затем добавит к ним path. Так что это становится user_employeurs_path. по соглашению он будет множить ваш последний объект (employeur), чтобы вывести имя вашего контроллера. вот так получается user_employeurs_path

поэтому вам придется либо использовать ресурсы вашего контроллера во множественном числе, чтобы следовать соглашению. Или передайте URL-адрес вашего пути:

<%= form_for [@user, @employeur],  url: user_employeur_path do |f| %>
person Wally Ali    schedule 27.05.2014