Possuo 3 models:
class Day < ApplicationRecord
belongs_to :goal
has_many :day_salesmen, dependent: :destroy
has_many :salesmen, through: :day_salesmen
validates_presence_of :date_day, :goal_id
accepts_nested_attributes_for :day_salesmen
end
class DaySalesman < ApplicationRecord
belongs_to :day
belongs_to :salesman
accepts_nested_attributes_for :salesman
end
class Salesman < ApplicationRecord
belongs_to :company
has_many :goal_salesmen, dependent: :destroy
has_many :goals, through: :goal_salesmen
has_many :day_salesmen, dependent: :destroy
has_many :days, through: :day_salesmen
end
Na minha aplicação eu tenho uma meta, essa meta pertence a uma empresa e tem data de início e final, quando ela é criada automaticamente são criados valores na tabela day que vão entre a data de início e data final definidos na meta, esse campo tem o nome de date_day.
Além desse campo cada Day possui um campo valor, que é o valor total arrecadado durante o dia, esse valor não é definido automáticamente quando o usuário cria uma meta, ou seja ele vem null, é necessário editar o Day para definir o quanto foi arrecadado naquele dia. Quando vou fazer a edição do day eu gostaria de adicionar um funcionário no meu model Salesman, esse funcionário estaria atrelado a aquele Day.
Eu consegui através do formulário de edição de Day adicionar um funcionário, mas só isso, a edição do valor da day não é atualizado e também não tenho incremento das tabelas DaySalesman.
Abaixo estão meus controllers e o resultado dos meus controllers:
class DaysController < ApplicationController
before_action :find_day, only: [:show, :edit, :update]
before_action :find_company, only: [:show, :edit]
def index
@day = current_owner.companies.find(params[:company_id]).goal.find(params[:goal_id]).days
end
def show
end
def edit
@dayup = Day.new
@day_salesmen = @dayup.day_salesmen.build
@salesman = @day_salesmen.build_salesman
end
def update
if @day.update(params_day)
flash[:notice] = "Day updated!"
redirect_to company_salesman_path(:id => @day.id)
else
flash.now[:error] = "Could not update day!"
render :edit
end
end
private
def find_company
@company = Company.find(params[:company_id])
end
def find_day
@day = Day.find(params[:id])
end
def params_day
params.require(:day).permit(:value, day_salesman_attributes: [:id, salesman_attributes:[:id, :name]]).merge(goal_id: params[:goal_id])
end
end
Salesman:
class SalesmenController < ApplicationController
before_action :find_salesman, only: [:edit, :update, :destroy]
def index
@salesmen = current_owner.companies.find(params[:company_id]).salesman
@company = Company.find(params[:company_id])
end
def create
@salesman = Salesman.new(params_salesman)
if @salesman.save
flash[:notice] = "Salesman saved!"
else
flash.now[:error] = "Cannot create salesman!"
render :new
end
end
def update
if @salesman.update(params_salesman)
flash[:notice] = "salesman updated!"
else
flash.now[:error] = "Could not update salesman!"
render :edit
end
end
def destroy
@salesman.destroy
end
private
def find_salesman
@salesman = Salesman.find(params[:id])
end
def params_salesman
params.require(:day).require(:salesman).permit(:name, :id).merge(company_id: params[:company_id])
end
end
A minha view edit do controller day é:
<%= render "shared/sidebar2" %>
<div class="container">
<div class="row">
<div class="col s10 offset-s2">
<div class="row">
<h4>Edit day</h4>
<%= form_for(@dayup, url: company_salesmen_path) do |f| %>
<%= f.label :value_of_day %>
<%= f.number_field :value %>
<%= f.fields_for :day_salesman do |ff| %>
<%= f.fields_for :salesman do |fff| %>
<%= fff.label :names_of_salesmen %>
<%= fff.text_field :name %>
<% end %>
<% end %>
<%= f.submit "Create" %>
<% end %>
</div>
</div>
</div>
</div>
O meu log quando eu clico no botão submit nessa view é:
Started POST "/companies/1/salesmen" for 172.26.0.1 at 2017-10-31 22:11:56 +0000
Cannot render console from 172.26.0.1! Allowed networks: 127.0.0.1, ::1, 127.0.0.0/127.255.255.255
Processing by SalesmenController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"CQaRlVPYsPK8ilOQJCdw04htgXFkUQOKEVsOIDAmRXOM1X3QO+HfOzY2PGnmItMTK9jRj0YFZDYRJPg7qBV27A==", "day"=>{"value"=>"100", "salesman"=>{"name"=>"Renata"}}, "commit"=>"Create", "company_id"=>"1"}
[1m[36mOwner Load (0.7ms)[0m [1m[34mSELECT "owners".* FROM "owners" WHERE "owners"."id" = $1 ORDER BY "owners"."id" ASC LIMIT $2[0m [["id", 1], ["LIMIT", 1]]
[1m[35m (12.4ms)[0m [1m[35mBEGIN[0m
[1m[36mCompany Load (0.4ms)[0m [1m[34mSELECT "companies".* FROM "companies" WHERE "companies"."id" = $1 LIMIT $2[0m [["id", 1], ["LIMIT", 1]]
[1m[35mSQL (111.1ms)[0m [1m[32mINSERT INTO "salesmen" ("name", "company_id", "created_at", "updated_at") VALUES ($1, $2, $3, $4) RETURNING "id"[0m [["name", "Renata"], ["company_id", 1], ["created_at", "2017-10-31 22:11:56.344478"], ["updated_at", "2017-10-31 22:11:56.344478"]]
[1m[35m (36.3ms)[0m [1m[35mCOMMIT[0m
No template found for SalesmenController#create, rendering head :no_content
Completed 204 No Content in 436ms (ActiveRecord: 161.0ms)
Queria saber como através desse form de edit da day eu posso atualizar o valor referente a day, criar um novo funcionário e associar ele a essa day através da tabela Daysalesmen.