0

I have 2 models, one is for Users, and the other is for Medications. Each user can have many medications. The user can create medications, but can't see medications other users made.

<% @medications.each do |medication| %>
      <tr>
        <td><%= medication.name %></td>
        <td><%= medication.user_id %> </td>  

Obviously this code doesn't do what I want, but how can I modify the first part to be a conditional that only works if current_user.id == medication.user_id?

0

3 Answers 3

1

Option1: In your controller, fetch only the current user's medications.

# user model
class User < ActiveRecord::Base
  has_many :medications # this needs to be in place
end

# in controller action that is rendering your view
@medications = current_user.medications

Option2: In your view, skip medications that don't have the current user's ID in their user_id column:

# view
<% @medications.each do |med| %>
  <% next if (med.user_id != current_user.id) %>
  <% # more code %>
<% end %>

And if you're showing parts of the medication based on the current user, then obviously:

# view
<% @medications.each do |med| %>
  <%= medication.name # example %>
  <% next if (med.user_id != current_user.id) %>
  <%= medication.reason # example %>
<% end %>

Unless you need to display other medications / other info as well, I'd go with Option1.

Sign up to request clarification or add additional context in comments.

Comments

1

Use a scope in your medication model so that you can find the current users medication and use it in other places as well:

   scope :users_medication, ->(current_user) { where user_id: current_user.id}

Then in your view call the class method you just defined on the Medication class and pass it the current user:

<% Medication.users_medication(current_user).each do |medication| %>
      <tr>
        <td><%= medication.name %></td>
        <td><%= medication.user_id %> </td>

Comments

0

In your controller

def show
   @user = User.find(params[:id])
   @medications = @user.medications
end

This will display only the medications of that particular user only

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.