【问题标题】:Ruby on Rails - Dropdown with Has Many relationshipRuby on Rails - 具有很多关系的下拉菜单
【发布时间】:2014-01-23 11:59:46
【问题描述】:

我的数据库中有四个表。一个是用户,另一个是组织。一个用户可以拥有多个组织,一个组织可以拥有多个用户。此关系存储在名为 user_organizations 的第三个表中,其中包含 user_id 和 organization_id 列。

第四个表称为 organization_details,我在其中存储有关组织的其他多行信息。

我想要发生的是:当登录用户想要将组织详细信息添加到他们通过 user_organizations 链接到的组织时,只有他们链接到的组织应该出现在下拉列表中。

我不确定该怎么做。系统通过current_user返回登录用户的信息,例如。

所以我正在尝试做这样的事情:

collection_select(:organization_detail, :organization_id, Organization.where({id: current_user.id...关于 user_organization 也在这里}), :id, :name_and_state)

解决此问题的最佳方法是什么?非常感谢!

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    您应该能够使用内置关联。由于用户 has_many 组织,您可以像这样调用current_user.organizations

    collection_select(:organization_detail, :organization_id, current_user.organizations, :id, :name_and_state)
    

    这假设您在模型中正确连接了所有内容。

    如果您不熟悉Rails Guide to associations,您还应该查看他们。

    【讨论】:

    • 哇,这比我做的要容易得多!谢谢谢谢!我一定会看看你提供的链接。我认为第三张表会更复杂。
    【解决方案2】:

    current_user.organizations 可以解决问题。

    您的下拉菜单如下所示:

    <ul>
      <%- current_user.organizations.each do |organization| -%>
        <li><%= link_to organization.name, your_path_here %></li>
      <%- end -%>
    </ul>
    

    【讨论】:

    • 非常感谢您的帮助;如果我走那条路,那看起来是下拉菜单的一个不错的选择。我讨厌我有时让事情变得比他们在 RoR 中需要的更复杂。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    • 2020-10-06
    • 2021-07-27
    • 2013-05-01
    • 1970-01-01
    • 2023-03-10
    相关资源
    最近更新 更多