表单上的Rails集合需要额外的(租户ID)字段



我进退两难。。。我已经组装了一个多租户应用程序,但我对一个表单和操作有问题。表单(配置文件(有一个集合select,用于选择适用的技能。Profile<-标记->标签。标记记录显示在集合中以供选择,并启用多选。

当您选择一些技能并保存配置文件记录时,在配置文件更新操作中,Rails抛出:

验证失败:租户必须存在

这似乎来自Tagging表,因为当我删除与Tenant的关系时,没有错误,配置文件记录保存成功。如果我直接从Rails控制台创建一个标记记录,那么tenant_id就会填充并保存该记录。

respond_to do |format|
if @profile.update(profile_params) < fails here
format.html { redirect_to profiles_path, notice: 'Profile was successfully updated.' }
format.json { render :show, status: :ok, location: @profile }
else

Params(如果我必须在这里插入tenant_id,我希望在标签id数组中,但如何?(:

{"utf8"=>"✓",
"_method"=>"patch",
"authenticity_token"=>"longobscurestring",
"profile"=>
{"description"=>"",
"tag_ids"=>
["",
"b39b38eb-a90b-434b-9457-1f3b67cee54e",
"08d90ee7-3194-4fec-acee-bcecfae1e8e7",
"ee8de96d-1206-4d73-bcf0-0b99f995569a",
"469ce954-b2bd-49d5-9dbc-0636b4da43c8",
"38b90691-d3f0-4c9d-8b5f-2c644a894d45",
"77a332d9-feed-4f88-8133-19066b5d33bc",
"05c145ce-a8ff-4105-a713-073da60184b5",
"8d6f98e3-9c3e-4f45-8c7d-36b177b557af"],
"contact_direct"=>"false"},
"commit"=>"Save",
"id"=>"1728fcc4-f2e2-49de-9a39-5c67502b8a85"}

配置文件形式:


<%= simple_form_for @profile, url: profile_path do |f| %>
<%= f.input :description, :as => :text, :input_html => {:cols=>100, :rows=>5} %>
<%= f.input :tag_ids, label: 'Skills', as: :select, collection: Tag.active.order(:name), label_method: :name, input_html: { multiple: true } %>
<div>
<span>People may contact me:</br></span>
<div class="radio-inline margin-10" style="text-align:left">
<%= f.input :contact_direct, label: '', as: :radio_buttons, collection: [['Directly', true], ['Through my manager', false]] %>
</div>
</div>
<br/>
<div class="actions">
<% if ( can? :manage, :all or current_user.id == @profile.user_id) %>
<%= f.button :submit, 'Save', class: "btn btn-success" %>
<% end %>
<%= link_to "Back", profiles_path(:search => {:column => 'First', :direction => 'Up', :name => ''}), class: "btn btn-primary link-as-button" %>
</div>
<% end %>

配置文件模型关联:

class Profile < ApplicationRecord
belongs_to :user
belongs_to :tenant
has_many :taggings, :dependent => :destroy
has_many :tags, through: :taggings

标记模型关联:

class Tagging < ApplicationRecord
attribute :competence, :integer, default: 0
belongs_to :tenant
belongs_to :tag
belongs_to :profile, optional: true
has_one :user, through: :profile
has_many :endorsements, inverse_of: 'tagging'
has_many :endorsers, through: :endorsements

所有表都通过pg策略实现了RLS。不过,如果标签记录上没有tenant_id,则可以通过另一个租户访问该记录。

请让我知道这里需要调试的任何其他内容。提前谢谢!

我通过在Tagging模型中添加一个after_initialize回调来解决这个问题:

def set_tenant_id
if new_record?
self.tenant_id = self.tag.tenant_id
end
end

如果这是不好的做法,请随意说。。。但我目前看不到其他办法。

最新更新