0

I'm new with ruby on rails and I'm blocked on a big problem. I create a User table and a Course table. A user if he is a student can register to a Course. So i have my join table which is courses_users with the id of my User and the id of my course.

In a view I displayed all my courses and with them i have a "register" button for each different course :

<%= button_to 'register', modules_path, method: :post, params: {course_id: course.id, user_id: current_user.id} %> 

And this gonna call my method Create :

def create @course_user = CoursesUser.new(course_params) @course_user.save redirect_to modules_path end 

So this will create my relation between the current user and the course_id I selected.

My problem is that how should I do to catch my relation and if this one already exist it will display an other button to Unregister from this course (similar to a follow / unfollow)

I tried with this :

@course_user = CoursesUser.where(user_id: current_user.id) 

but i dont know how to make a condition in my view.

I dont know if i'm precise enought but if someone know how to solve it, it would be really nice !

2 Answers 2

0

You must have an association in user.rb

User has_many :courses 

Now you can get the list of user courses

<% if current_user.course_ids.include?(course.id) %> <%= button_to 'unregister', .... %> <% else %> <%= button_to 'register', modules_path, method: :post, params: {course_id: course.id, user_id: current_user.id} %> <% end %> 
Sign up to request clarification or add additional context in comments.

Comments

0

if your @course_user instance returns the value you expect then your view should look like

<% if @course_user.blank? %> <%= button_to 'register', modules_path, method: :post, params: course_id: course.id, user_id: current_user.id} %> <% else %> #your unregister/unfollow link <% end %> 

Good luck.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.