【发布时间】:2016-03-31 04:16:26
【问题描述】:
我有一个连接表,连接一个客户端和一个 Setor(复数:setores)模型。关系是一个 Client has_and_belongs_to_many Setores(有三个 Setores,一个 Client 可以有一个到所有三个。Setores 有很多客户)。
我的问题是: 在这个连接表中,我添加了对 User 模型的引用。 Setores 有很多用户,但是一个客户和一个 setor 之间的关系只有一个用户。但我不知道如何在clients_setores 表上读写这个关联。
我的模型如下:
class Client < ActiveRecord::Base
has_and_belongs_to_many :documents
has_and_belongs_to_many :setores
has_many :screenings
has_many :contacts
has_many :interactions, through: :contacts
validates :cnpj, uniqueness: true
class Setor < ActiveRecord::Base
self.table_name = 'setores'
has_many :documents
has_many :screenings
has_many :users
has_and_belongs_to_many :clients
attr_acessor :user_id
class User < ActiveRecord::Base
has_one :setores
has_many :clients
并且当前正在工作的连接表参数在客户端控制器的末端显示如下:
private
# Use callbacks to share common setup or constraints between actions.
def set_client
@client = Client.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def client_params
params.require(:client).permit(:cnpj, :pacote, :razsoc, :vencimento, user_ids:[], document_ids:[], setor_ids:[])
end
请注意,“user_ids:[]”是我试图让它工作的尝试,但到目前为止失败了。
在视图中,我使用这样的当前连接表(取自 /client/_form.html.erb):
<%= f.collection_check_boxes :setor_ids, Setor.where(pacote: true), :id, :setor do |b| %>
因此,通过这些复选框,我可以在 clients_setores 表中创建一个条目。
我想要做的是能够从下拉菜单中选择属于给定 setor_id 的用户并将此关系存储在连接表中。我确实设法使这样的菜单出现在同一个 _form.html.erb 中,并带有以下代码:
<%= f.collection_select :user_ids, User.where(:setor_id => 1), :id, :email %>
但是当我提交表单时,没有保存值。我不知道我的问题是否只是因为我没有正确的方法在我的视图中记录此关联,或者我的问题是否在控制器(可能)和模型(可能)中更进一步。
我在 SO 中发现的最接近的问题是 Rails 4 Accessing Join Table Attributes,但关联类型不同(has_many/through)并且不涉及第三个关系,所以我不知道如何让它为我工作。
【问题讨论】:
-
嘿,我没有完全理解你的问题,所以如果你能澄清“我的问题是:在这个连接表中我添加了对用户模型的引用”的意思。 has_and_belongs_to_many 仅允许两列(setor 和 client 表的外键),因此如果您说要添加对该表的引用,则必须使用“has_many through”设置。此外,您没有将您的客户属于您的客户模型中的用户。
-
对于一个拥有多个用户的客户端,它必须通过相同数量的 Setores(1 个 setor:1 个客户端;3 个 setores:3 个客户端),has_many/through 关系是否像这样工作?至于属于User的Client,永远属于Setores一样多的User;这相关吗?
-
好吧,你是说如果一个客户有一个用户,他也必须有一个 setore?抱歉,我仍然不确定您要做什么,但是如果您需要一种方法来确保客户端和 setores 也同时了解用户,您将需要使用“has_many through”关联,以便您可以向该联接表添加其他列以存储有关用户的额外信息。
-
没错。在该系统的逻辑顺序中,必须首先为客户分配一个 Setor,然后才能分配一个用户(来自所述 Setor)。 (Setor 的意思是“部门”。如果我的客户需要应付账款部门的服务,它会从这个部门得到一个帮助)
标签: mysql ruby-on-rails ruby