【发布时间】:2016-03-09 15:23:19
【问题描述】:
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 %>
【问题讨论】:
标签: ruby-on-rails ruby ruby-on-rails-4