D
D
dexdev2015-09-19 17:05:49
Ruby on Rails
dexdev, 2015-09-19 17:05:49

How to properly organize a nested form for three models?

Good afternoon!
There are companies, companies can have many users, users can have many companies, users in each company have one position.
How to properly format the form in order to be able to edit the post?
Model Position = Position
base made like this:
id|user_id|company_id|name|

class Company < ActiveRecord::Base
  has_many :users_companies
  has_many :users, through: :users_companies
  has_many :positions
end

class User < ActiveRecord::Base
  has_many :companies, through: :users_companies
  has_many :users_companies
  has_many :positions
end

class Position < ActiveRecord::Base
  belongs_to :user
  belongs_to :company
end

class UsersController < ApplicationController
  def edit
    @company = Company.find(params[:company_id])
    @user = User.find(params[:id])
  end
  def update
    @user = User.find(params[:id])
    if @user.update(user_params)
      redirect_to :back
    end
  end
  private
  def user_params
    params.require(:user).permit(:last_name, :first_name, :middle_name)
  end
end

I make a form and all positions from all companies are displayed on it
<%= form_for @user do |f| %>
<%= f.label :last_name, "Фамилия" %><br />
    <%= f.text_field :last_name, type: "text" %>

    <%= f.label :first_name, "Имя" %><br />
    <%= f.text_field :first_name, type: "text" %>

    <%= f.label :middle_name, "Отчество" %><br />
    <%= f.text_field :middle_name, type: "text" %>
    <%= f.fields_for :positions do |ff| %>
    <%= ff.label :name, "Должность" %>
    <%= ff.text_field :name, type: "text" %>
    <%= ff.hidden_field :company_id, value: @company.id %>
    <% end %>
    <%= f.submit "Сохранить", class: "login loginmodal-submit", type: "submit"  %>
<% end %>

How to make a form so that you can edit an existing record belonging to the current company?

Answer the question

In order to leave comments, you need to log in

3 answer(s)
J
jarosluv, 2015-09-22
@AdilA

If I understand the question correctly, then in the simplest case:

#controller
@position = Position.find_by(user: params[:id], company: params[:company_id])

#view
<%= f.fields_for :positions, @position do |ff| %>

Also don't forget to fix the User model and user_params in the controller.
api.rubyonrails.org/classes/ActiveRecord/NestedAtt...

O
O Di, 2015-09-19
@insiki

Seems to be your case:
Ruby on Rails - Railscasts PRO #196 Nested Model F...

Z
Zaporozhchenko Oleg, 2015-09-19
@c3gdlk

To display only company positions, you need to explicitly set them in the controller
But, I don't think that will work, because the retention will likely erase other companies' positions.
In this case, it's easier to write this logic explicitly

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question