I have an app that allows users to add courses to their profile. This is done through my ‘lineups’ model. To give you an idea of my database and schema:
#relationships
Class User
has_many :lineups
end
Class Course
has_many :lineups
end
Class Lineup
belongs_to :user
belongs_to :course
end
#some schema
create_table "lineups", :force => true do |t|
t.integer "course_id"
t.integer "user_id"
end
Now, I have a page were courses are listed with an ‘add course’ button. When clicked, a form submits to my ‘Lineup’ controller to the ‘create’ action. This process works great, however, my code that checks to see if a user has already added a course fails. The course will be added again. Here is my controller code:
class LineupsController < ApplicationController
def create
course_id = params[:course_id]
user_id = current_user.id
course_object = Course.find(course_id)
#THIS BLOCK DOES NOT WORK
for lineup in current_user.lineups do
if lineup.course.id == course_id
return redirect_to course_query_url, :alert => "You have already added this course: #{course_object.cl} #{course_object.cn}"
end
end
#THE BLOCK ^^^ DOES NOT WORK
new_lineup = Lineup.new( course_id: course_id, user_id: user_id)
respond_to do |format|
if new_lineup.save
format.html { redirect_to course_query_url, :notice => "Course added: #{course_object.cl} #{course_object.cn}" }
else
format.html { redirect_to course_query_url, :alert => "There was an error in adding the course: #{course_object.cl} #{course_object.cn}" }
end
end
end
end
I know that this line works, b/c I have it working in a view:
for lineup in current_user.lineups do
And I know that when the above line is iterated, the ‘lineup’ instance is created and the relationships work find (ie ‘lineup.course.id’) b/c it is also used in a view. Here is the code from the view in which this loop works:
<% if current_user.lineups %>
<% for lineup in current_user.lineups do %>
<li><%= link_to "#{lineup.course.id} #{lineup.course.cn}", index_path %></li>
<% end %>
<% end %>
I am really at my wits end here and cannot figure out why this conditional is not working. Any and all input would be appreciated.
Your are comparing number (course.id) and string (params[:id]) in this line
This does not work in Ruby 🙂
Try to change to
or