New for rails and rubies. Fight with form_forand associations. I am trying to configure a rails application that allows a user to select from a list of clients. Customers are connected through relationships has_many :through. I have models working as expected, and I can add clients to users through the rails console. Now I want to move this feature to the web interface. Below is the code as I tried, but that just doesn't make sense to me. I'm not sure which controller action is the right action. Do I have to process the form POSTin client action? I really do not want to create a new client, I just want the user to select existing clients from the list and create an association.
My models:
class Client < ActiveRecord::Base
has_many :users, :through => :user_clients
has_many :user_clients, :dependent => :destroy
end
class User < ActiveRecord::Base
has_many :clients, :through => :user_clients
has_many :user_clients, :dependent => :destroy
end
class UserClient < ActiveRecord::Base
belongs_to :user
belongs_to :client
end
Routes as follows
resources :clients do
resources :users
end
resources :users do
resources :clients
end
class ClientsController < ApplicationController
before_action :set_client, only: [:show, :edit, :update, :destroy]
def index
if params[:user_id]
@clients = User.find_by_id(params[:user_id]).clients
else
@clients = Client.all
end
@clients
end
def create
if params[:user_id]
user = User.find(params[:user_id])
client = Client.find_by_id(params[:client_id])
user.clients << client
user.save
redirect_to users_url
else
@client = Client.new(client_params)
@client.save
redirect_to clients_url
end
end
end
<h1>new.html.erb</h1>
<% if params[:user_id] %>
<%= form_for([@user,@client]) do |f| %>
<div class="field">
<%= f.label :id %><br>
<%= f.text_field :id %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
<% else %>
<%= render 'form' %>
<% end %>