在 rails 中选择 table 中的特定行

Choosing a specific row in a table in rails

我有一个迁移和模型,其中 table 称为药物。我需要从药物 table 中选择特定的一行。我也在尝试过滤掉所有没有当前用户 ID 的药物。

这是我当前的代码。

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

我知道这还不完整,但我们将不胜感激任何帮助。

如果您还没有设置,这是 has_many :through 关联的完美用例。

class User < ActiveRecord::Base
  has_many :prescriptions # or whatever
  has_many :medications, :through => :prescriptions
end

class Prescription < ActiveRecord::Base
  belongs_to :user
  belongs_to :medication
end

class Medication < ActiveRecord::Base
  has_many :prescriptions
  has_many :users, :through => :prescriptions
end

现在您可以执行以下操作:@user.medications 仅检索该用户的药物,@user.medications.find(params[:medication_id] 在用户分配的药物中查找特定药物,以及 @user.medications << Medication.find_by(name: 'Aspirin') 添加药物到用户等。

这是此技术的基本概述,但它是一个基本的 Rails 概念,因此有大量关于用例的信息与您可能尝试做的任何事情很接近。

您可以像这样加载特定 user_id 的第一种药物(假设您的药物 table 具有 user_id):

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

如果我们的 User 模型有一个 belongs_to :medications 它可以简化为:

current_user.medications.order(:name).first

如果你想加载例如第 5 种药物只需添加 4 的偏移量:

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

或者加载所有药物并遍历它们:

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

如果你想在网站上输出前十种药物,你可以这样做:

# 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>

您使用的查找器语法已弃用并在 Rails 4 中被替换。参见 Rails Guide about querying the database

我解决了这个问题,我决定 post 答案以防其他人遇到类似问题。

我最终没有在我的控制器中放置任何东西,也没有向我的模型添加任何新东西。我只是在视图中使用了这行代码。

<%= Medication.offset(0).where(:user_id => current_user.id).pluck(:name).first %>

没有大家post编者的支持,我不可能做到,谢谢!