I have 3 forms in a view called 'home' each form submit different model, each form redirect to a create action in the respective controller. After create each controller redirect to the administration view which also index each model and provide edit and delete links.
I don't know if this approach is a good practice since i have to instance all in the administrators_controller, also i have to instance each model in their respective controllers again.
administrators_controller.rb
def home
@user = Employee.new(role: :emp)
@market = Market.find(params[:market_id])
#INDEX EMPLOYEE:
@employees = @market.users.where(role: :emp)
#INDEX SERVERS:
@server = Server.new(market_id: @market.id)
@servers = @market.servers
#INDEX TRAMITES:
@task = Task.new(market_id: @market.id)
@tasks = @market.tasks
end
users_controller.rb
def edit
@user = User.find(params[:id])
end
def update
@user = User.find(params[:id])
if @user.update_attribute(:email, params[:user][:email])
flash[:success] = "User updated"
redirect_to market_admin_path(current_user.market_id)
else
render 'edit'
end
end
home.html.erb
<% provide(:button_text, 'create') %>
<%= render 'users/form', url: market_employees_path %>
<h1> Empleados: </h1>
<% @employees.each do |employee| %>
<ul>
<li><%= employee.email%> <%= link_to 'edit', edit_user_path(employee) %></li>
</ul>
<% end %>
<br>
<h1> Servers: </h1>
<table style="width:100%">
<tr>
<th>ID</th>
<th>Descripcion</th>
</tr>
<%= render 'servers/form', url: market_servers_path %>
<% @servers.each do |serv| %>
<tr>
<td><%= serv.id%></td>
<td><%= serv.description%> <%= link_to 'edit', edit_server_path(serv) %></td>
</tr>
<% end %>
</table>
<h1> Tramites: </h1>
<%= render 'tasks/form', url: market_tasks_path %>
<table style="width:100%">
<tr>
<th>ID</th>
<th>Descripcion</th>
<th>Duracion</th>
</tr>
<% @tasks.each do |task| %>
<tr>
<td><%= task.id%></td>
<td><%= task.name%></td>
<td><%= task.duration%> <%= link_to 'edit', edit_task_path(task) %></td>
</tr>
<% end %>
</table>
users/_form.html.erb
<%= form_for(@user, url: local_assigns[:url]) do |f| %>
<%= render 'shared/flash_type', type: 'employee'%>
<%= f.hidden_field :role %>
<%= f.email_field :email, class: 'form-control' %>
<%= f.submit yield(:button_text), class: "btn btn-primary" %>
<% end %>
routes.rb
resources :markets, only: [], shallow: true do
resources :employees, only: [:create]
resources :users, only: [:edit, :update]
resources :tasks, only: [:create, :edit, :update]
resources :servers, only: [:create, :edit, :update]
get '/administration', :to => 'administrators#home', :as => :admin
end
It actually works but i would like to know if there is a better way to do this.
Note: 'employee' class was created to use form objects pattern
Aucun commentaire:
Enregistrer un commentaire