我的第一个问题!我试图把“关键公司”分配给我的用户。这些内容可以在many-to-many富连接表中找到。在这个表中有一些属性,如new、key、active等等。我想在一个长长的列表中给用户分配公司,为此我使用SimpleForm。
除了我想根据丰富关系上的属性过滤和限制关联关系之外,一切都正常工作。我对每个用户都有公司关系,但不是所有用户都是key-relation或new-relation。我只想让key这个协会出现,而不去碰其他的。当我将这些公司分配给用户时,我还想将属性active设置为true。我的代码现在看起来如下:
user.rb
class User < ActiveRecord::Base
has_many :company_user_relationships
has_many :companies, through: :company_user_relationshipscompany.rb
class Company < ActiveRecord::Base
has_many :company_user_relationships
has_many :users, through: :company_user_relationshipsschema.rb
create_table "company_user_relationships", force: true do |t|
t.integer "company_id"
t.integer "user_id"
t.boolean "key"
t.boolean "active"
t.datetime "last_contacted"
t.string "status_comment"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "status"
t.boolean "new"
endusers_controller.rb
def assign_key_companies
User.update(params[:users].keys, params[:users].values)
redirect_to(:back)
end视图
= form_for :user_companies,
url: assign_key_companies_users_path,
html: {:method => :put} do |f|
- users.each do |user|
= simple_fields_for "users[]", user do |u|
tr
td.col-md-4
= "#{user.first_name} #{user.last_name}"
td.col-md-8
= u.association :companies, label: false, collection: @key_company_candidates,
input_html: {data: {placeholder: " Assign key companies"}, class: 'chosen-select'}
= submit_tag "Save key companies", class: "btn btn-success pull-right"我基本上只想显示user.companies.where(key: true)和SQLCOMMIT,以便在更新记录时始终将key-field放到true上。
如何筛选出只影响我想要的关联?
发布于 2016-07-15 13:02:45
我能想到两种方法。
首先在关联级别过滤它
class User < ActiveRecord::Base
has_many :company_user_relationships, -> { where("company_user_relationships.key" => true) }或者一个地方
user.companies.where("company_user_relationships.key" => true)当您调用user.companies时,它实际上在所有三个表中执行连接表,因此您可以像我的示例那样指定条件。
https://stackoverflow.com/questions/38395716
复制相似问题