Ruby on Rails - Dropdown with Has Many relationship - ruby-on-rails

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!

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.

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>

Related

Rails 5 nested form find or create

I have two models Run and Patient. Run belongs_to Patient and Patient has_many runs.
On the Run model I'm using accepts_nested_attributes in which to enter a patient's information into a run via a regular Rails form using fields_for.
Right now I have a basic form (stripped down version) that looks like this:
<%= form_for(#run) do |f| %>
<%= f.fields_for :patient do |p| %>
<%= p.text_field :patient_name, placeholder: 'John Doe', class: 'form-control' %>
<% end %>
<% end %>
I'm able to create a patient inside of the form and reject the associated/nested object created inside of the model. But what i'm looking to do is:
1.) Have a search/select box where I can type a patient name in and it will autocomplete
2.) If it finds the patient, it selects the patient and uses it for the run.
3.) If it does not find the patient or it's not the right patient, I'd like to be able to use first_or_create somehow to create the new patient record tied to the run.
I have searched for some examples on this and have come up short except an old Railscast espisode which wasn't very helpful and uses jQuery autocomplete which I'd like to avoid (use selectize or select2 instead).
I will continue working on examples that I find online, but any suggestions on how to do this is what I'm looking for. I feel that I can instantiate the patients from a collection within the controller and use those in a selectize/select2 box to choose the patient and the associated nested field of patient_id. So selecting the patient would not be a problem, but I'm unsure as to how to tackle the creation of a patient that does not match.
This answered my question:
https://gorails.com/episodes/select-or-create-with-selectize-js
I was able to get the behavior down that I needed using this.

Ruby on Rails - Single Sign Up and Login Form for Two Different User Types and handling the Session

I'm currently pretty new to Ruby on Rails, but right now I'm trying to set up a simple platform to create events, manage those events, and purchase tickets to those events. I have two different user types:
Manager:
has_many: events
(with params):
email
password
organization_name
Fan:
has_many: tickets
(with params):
email
password
name
cell_phone
I have two different partials containing sign-up forms for both Managers and Fans. My thought process right now is to have a param called #is_manager in the session that allows my sign-up form to dynamically hide/reveal the partials and to handle logic in the controller.
The sign-in form for both models will be identical, as they can both login using their emails and passwords. My current thought for this is to either include an additional checkbox which filters attempted logins to either the Fan or Manager database, or to require emails to be unique across both databases.
I've looked at a large number of other stack overflow questions, and have looked into Devise (which I was cautioned against while I still don't have a strong handling of Ruby on Rails), as well as some JQuery solutions to dynamically changing this session param, but I haven't found a solution which I feel applies well to me.
Thoughts?
(My current sign-up form code is something like below:)
<h1>Signup</h1>
<h3>Are you a manager?</h3>
<%= link_to_function "Yes", "magic_javascript_function" %>
<%= link_to_function "No", "magic_javascript_function" %>
<%= form_for :session, url: signup_path, method: :post do |f| %>
<%= render 'manager_signup', :f => f if #is_manager %>
<%= render 'user_signup', :f => f unless #is_manager %>
<%= f.submit 'Submit', class: "btn btn-primary" %>
<% end %>
If your new to RoR I highly advise going to The Rails Tutorial by Michael Hartl's railstutorial.org.
I recomend this tutorial because he shows how to create a user model with login sessions etc. without using devise or cancan and this gives excelent insight into what those programs are used for and how they work so you can use them later.
In regards to your specific case I would argue this: What if a member who has only acted as a manger wants to go to another managers event. Would he then need a separate fan account. Alternatively what if a member who has only been a fan wants to organize a local event for his garage band.
See where I am going with this. It might be best for a login/signup page to be agnostic towards these roles.
Where you could use these roles however is in you relationships
here you could do something like this
User.rb
has_many: events
has_many: tickets
Event.rb
belongs_to: manager, class_name: "User"
has_many: tickets
Ticket.rb
belongs_to: event
belongs_to: fan, class_name: "User"
Check the belongs_to api if it this gives you trouble you may need to explicitly set the foreign key.

Rails 4 site-wide filter records

Is it somehow possible to filter database records site wide? My models are league, match, team, player and detail. Now I would like when I enter the site and select a league that everything on the site is only displaying data for this specific league.
My relations are:
league has_many matches
match belongs_to team1
match belongs_to team2
team has_many players
player has_many details
Would that be possible?
You could do it like this:
Principle
If the league option is going to be the main decider of the content on your app, you might want to design around the league model
To do this, you'd make your root the league controller, and then show data based on the league's associated content
I.E instead of Team.joins(:league).where(league: "x"), you would do:
#Leagues
league = League.find(x)
league.matches
This would mean you could load the league directly from the database, making it much simpler for the user
Nested Resources
The alternative to this is to use the nested resources method that Michael Szyndel recommended in his comment. This would make it so you'd have to visit the URLs as follows:
domain.com/leagues/1/matches/2/teams/1
The benefit of this would be to DRY up your code, but it would add lots of extra levels to your system, which you may not want. I'll give an overview of what I'd look at below:
Code
#config/routes.rb
root to: "leagues#index"
#app/controllers/leagues_controller.rb
def index
league = params[:league] ? params[:league] : "0"
#league = League.find(league)
end
#app/views/league/index.html.erb
<%= form_tag('/') do %>
<%= select_tag 'league', options_for_select(League.all.collect {|u| [u.name, u.id] }) %>
<% end %>
<% #league.matches.each do |match| %>
<%= "#{match.team_1.name} vs #{match.team_2.name} : #{match.created_at}" %>
<% end %>
This would need to be re-factored & extended to include match details, make the "league" a session variable etc, but as the question might be closed, I thought I'd give you some ideas
The bottom line is that it comes down to how you want the app to function

ruby on rails get table row by two column conditions

For instance, I have two tables in database, Users and Microposts. The Users table stores all the users and has two columns, id and name; the Microposts table stores the posts made by the Users and has three columns: id, post_content and user_id (These two tables, of course, have the timestamp as each entry is created). So basically what I want is have a view page that displays the information stored in Users (id and name) plus the last post created by the corresponding user.
One way I'm thinking of doing is to have it being processed right at the user view page (located in, for example, app/views/Users/index.html.erb). Since I'm probably going to loop through the Users table like this
<% #Users.each do |user| %>
id = user.id
<!-- Do such and such -->
<% end %>
and while looping through the Users table, use the user.id to get the latest post made by the user.
Second way is to basically implement such that the Users table has another column that store the latest post information and updates each time when a transaction is made to the database. So then when implementing the latest post can just be accessed as an attribute.
However, I don't really know which way is better nor how to implement either way...
Any suggestion?
Thanks in advance!
Edit:
Sorry, there is a typo. It's "two tables and one database"
Similar to the other answers but I wanted to add an important little piece that I feel is commonly overlooked. Including the association on the first call to the database.
# not sure the scale of your project but I would paginate #users
# by using includes you prevent the N+1 issues
<% #users.includes(:microposts).each do |user| %>
id = user.id
user.microposts.last
<% end %>
For some documentation on this:
http://guides.rubyonrails.org/active_record_querying.html#eager-loading-associations
class User
has_many :microposts
end
class Micropost
belong_to :user
end
# to get user's post
# for single user
#user.microposts
# for many users
#users.each do |user|
user.microposts.each do |post|
post.post_content
end
end
Your user has many microposts. So do the following on users view page i.e. app/views/Users/index.html.erb
<% #Users.each do |user| %>
id = user.id
last_post = user.microposts.last <!-- This will give you last post created by the user -->
<% end %>

Single Table Inheritance routing?

I have single table inheritance working just fine for my app. I have two user subtypes (Athlete and Company) that inherit the super-type User.
Let's say I am listing all users, and want a link to each user's profile from this list. I want to link to the athletes controller if the type is athlete and the companies controller if the type is company. Is there a standard Rails way to this? Maybe some routing tricks?
you can even do that much simpler, Rails recognizes which type of user it has to deal with, so let's say you have the instance variable #user wich can either be an Athlete or a Company, you can just do that
= link_to "Profile", #user
BAM! Rails magic!
<% User.find(:all).each do |user| %>
<%= link_to "user", eval("#{user.type.underscore}_path(user)") %>
<% end %>
This will generate a path according to the type of the user (stored in type field). Don't forget to add the type of users to your routes configuration.
I hope this helps.
regards

Resources