我有一个迁移模型和一张名为药物的桌子。我要从药物桌上挑一排。我也试图过滤掉所有没有当前用户id的药物。
这是我现在的代码。
Medication.find(:name, :conditions => { :user_id => current_user.id }, :order => "Medication.name")我知道这是不完整的,但任何帮助都将不胜感激。
发布于 2015-02-20 23:09:11
您可以为这样的特定user_id加载第一种药物(假设您的medications表有一个user_id):
Medication.where(user_id: current_user.id).order(:name).first当我们的User模型有一个belongs_to :medications时,它可以简化为:
current_user.medications.order(:name).first当您想加载例如第五种药物时,只需添加一个偏移量为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>您使用的finder语法被废弃,并在Rails 4中被替换。参见关于查询数据库的Rails指南。
发布于 2015-02-20 22:58:35
如果您还没有设置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概念,因此有大量关于用例的信息,这些信息与您可能试图做的任何事情都很接近。
发布于 2015-02-22 17:54:31
我解决了这个问题,我决定贴出答案,以防其他人出现类似的问题。
最后,我没有把任何东西放在我的控制器或添加任何新的我的模型。我只是在视图中使用了这一行代码。
<%= Medication.offset(0).where(:user_id => current_user.id).pluck(:name).first %>没有大家的支持,我不可能做到这一点,谢谢!
https://stackoverflow.com/questions/28639566
复制相似问题