Rails:如何从has_many关系中获取集合?

时间:2017-01-03 03:58:07

标签: ruby-on-rails

用户所属_来源
来源has_many用户

users_controller.rb

public override DesignerActionItemCollection GetSortedActionItems()
{
    DesignerActionItemCollection actionItems = new DesignerActionItemCollection();

    //adds the new smart tag action items.
    actionItems.Add(new DesignerActionHeaderItem("MySmartTag Support"));
    actionItems.Add(new DesignerActionPropertyItem("BackColor", "Back Color"));
    actionItems.Add(new DesignerActionPropertyItem("ForeColor", "Fore Color"));

    //adds the action items from base smart tag.
    foreach (DesignerActionItem baseItem in base.GetSortedActionItems())
    {
        actionItems.Add(baseItem);
    }
    return actionItems;
}

如何获取@users所属的源@users = User.where('u_company = "IBM" ') 的集合?

3 个答案:

答案 0 :(得分:1)

你需要通过连接获取源:

@sources = Source.includes(:users).where(users: {id: @users})

如果您不需要单独收集@users,那么您可以按如下方式运行单个查询:

@sources = Source.includes(:users).where(users: {u_company: 'IBM'})

答案 1 :(得分:1)

构建此关联的常用Rails方法是在User模型上有一个class User < ActiveRecord::Base belongs_to :source end class Source < ActiveRecord::Base has_many :users end @source = Source.find_by_name('IBM') # assumes that the IBM value is stored in the :name column # => #<Source id: 123, name: "IBM"> @users = @source.users # => [#<User id: 456, source_id: 123>, #<User id: 457, source_id: 123>] # or... @users = User.where(source_id: @source.id) 列,以便您可以检索相关记录,例如:

class User < ActiveRecord::Base
  belongs_to :source, primary_key: 'name', foreign_key: 'u_company'
end

class Source < ActiveRecord::Base
  has_many :users, primary_key: 'name', foreign_key: 'u_company'
end

但是,如果您没有在数据库中将记录与id-columns关联的默认列设置,则需要指定要用于调用的列。例如:

:name

上述示例再次假设源名称存储在@source = Source.find_by_name('IBM') # assumes that the IBM value is stored in the :name column # => #<Source id: 123, name: "IBM"> @users = @source.users # => [#<User id: 456, u_company: "IBM">, #<User id: 457, u_company: "IBM">] 列中。

extension UITextField {

    func useUnderLine() {

        ....

        superview?.backgroundColor = .clear

        let view = superview?.superview
        view?.subviews.first?.alpha = 0
        view?.backgroundColor = .clear

    }

}

如果您想了解更多详细信息,那么您必须提供有关数据结构以及如何将它们链接在一起的更多信息。

答案 2 :(得分:1)

我认为

@sources = @users.includes(:source).map(&:source).uniq

是你想要的