在has_many中使用collection<< object函数时如何获取中间对象:通过关系 [英] How do I get the intermediate object when using collection<<object function in has_many :through relationships
问题描述
定义has_many:through关系后,
After having defined a has_many :through relationship,
@user = User.New(:name=>"Bob")
@project = Project.New( :name=>"Market Survey")
@user.projects << @project
是否有一种简单的方法来获取它创建的新的中间对象?例如上面的示例,如果中间表是"memberships",那么我可以使用:
Is there an easy way to fetch the new intermediate object it creates? such as in the above example, if the intermediate table is `memberships' then I could use:
@membership = @user.projects << @project
我觉得必须有比我们一直做的更好的方法,即
I have this feeling that there must be a better way of doing this than what we do all the time, i.e
@membership = Membership.where(:user_id=>x , :project_id=>y).first
推荐答案
据我所知,没有魔术"方法可以做到这一点.如果您正在寻找比目前为止做得更好的东西,那么我能想到的最好的办法就是做这样的事情:
There's no 'magic' way of doing this that I'm aware of. If you're looking for something that reads better than what you've done so far, the best I can come up with is to do something like this:
class User < ActiveRecord::Base
# ... other active record stuff here.
def membership_for(project)
memberships.where(:project_id => project.id).first
end
end
# Somewhere else...
@user = User.new(:name=>"Bob")
@project = Project.new(:name=>"Market Survey")
@user.projects << @project
@user.save!
membership = @user.membership_for(@project)
不够完美,并且需要其他代码,但是它的读起来比您当前的代码要好,并且在Ruby中非常重要.
Not perfect, and requires additional code, but it does read better than your current code, and that counts for a lot in Ruby.
这篇关于在has_many中使用collection<< object函数时如何获取中间对象:通过关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!