Answer the question
In order to leave comments, you need to log in
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
<%= 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 %>
Answer the question
In order to leave comments, you need to log in
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| %>
Seems to be your case:
Ruby on Rails - Railscasts PRO #196 Nested Model F...
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 questionAsk a Question
731 491 924 answers to any question