Rails 和 ruby 新手。挣扎着form_for
和协会。我正在尝试设置一个 Rails 应用程序,允许用户从客户端列表中进行选择。客户通过以下方式关联has_many :through
关系。我让模型按预期工作,并且我可以通过 Rails 控制台向用户添加客户端。我现在想将此功能移至 Web 界面。下面的代码是我尝试过的方法,但对我来说没有意义。我不确定哪个控制器操作是正确的操作。我应该处理表格吗POST
在客户端的创建操作中?我实际上并不是想创建新客户端,我只是希望用户从现有客户端列表中进行选择并创建关联。
我的模型如下:
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
路线如下
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 %>