Search code examples
ruby-on-railsrubyruby-on-rails-4modelrails-activerecord

Choosing a specific row in a table in rails


I have a migration and model with a table called medications. I need to pick a specific row from the medications table. I also am trying to filter out all medications that don't have the current user's id.

Here is the current code I have.

Medication.find(:name, :conditions => { :user_id => current_user.id }, :order => "Medication.name")

I know this isn't complete, but any help would be greatly appreciated.


Solution

  • You can load the first medication for a specific user_id like this (assuming that your medications table has an user_id):

    Medication.where(user_id: current_user.id).order(:name).first
    

    When our User model has a belongs_to :medications it can be simplified to:

    current_user.medications.order(:name).first
    

    When you want to load the e.g. 5th medication just add an offset of 4:

    current_user.medications.order(:name).offest(4).first
    

    Or load all medications and iterate through them:

    current_user.medications.limit(10).each do |medication|
      puts medication.name
    end
    

    When you want to output the first ten medications on a website you would do something like this:

    # in the controller
    @medications = current_user.medications.order(:name).limit(10)
    
    # in the view
    <ul>
      <% @medications.each do |medication| %>
        <li><%= medication.name %></li>
      < end %>
    </ul>
    

    The finder syntax you use is deprecated and was replaced in Rails 4. See Rails Guide about querying the database.