Reputation: 824
I have four tables in my database. One is users, another is organizations. One user can have many organizations, and one organization can have many users. This relationship is stored in a third table, called user_organizations, with columns user_id and organization_id.
The fourth table is called organization_details, where I store additional, multi-row information about the organization.
What I want to happen is this: when a signed in user wants to add organization details to an org they are linked to through user_organizations, only the organizations they are linked to should appear in the dropdown list.
I am unsure of how to go about this. The system returns information about the signed in user through current_user, for example <%= current_user.first_name %>.
So I'm trying to do something like this:
collection_select(:organization_detail, :organization_id, Organization.where({id: current_user.id...something something about user_organization being here too}), :id, :name_and_state)
What is the best way to approach this? Thank you very much!
Upvotes: 0
Views: 173
Reputation:
current_user.organizations
will do the trick.
your dropdown would look something like this:
<ul>
<%- current_user.organizations.each do |organization| -%>
<li><%= link_to organization.name, your_path_here %></li>
<%- end -%>
</ul>
Upvotes: 0
Reputation: 5721
You should be able to use the built in association. Since User has_many Organizations you can call current_user.organizations
like this:
collection_select(:organization_detail, :organization_id, current_user.organizations, :id, :name_and_state)
This assumes you have everything hooked up correctly in the models.
You should also check out the Rails Guide to associations if you are new to them.
Upvotes: 2