2

After having defined a has_many :through relationship,

@user = User.New(:name=>"Bob")
@project = Project.New( :name=>"Market Survey")
@user.projects << @project

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

This should work in most browsers:

var languageinfo = navigator.language ? navigator.language : navigator.userLanguage;
if(languageinfo.split('-')[0] == 'es') {
    alert('hola')
} else {
    alert('hi');
}
4

3 回答 3

3

我知道没有“神奇”的方法可以做到这一点。如果您正在寻找比您迄今为止所做的更好的东西,我能想到的最好的方法是做这样的事情:

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 中很重要。

于 2012-11-14T07:01:02.550 回答
0

您可以执行以下操作:

@membership = @user.members.find_by_project_id(@project.id)

不确定它是否比你做的更容易/更好。

于 2012-11-13T22:35:11.633 回答
0

我不确定我是否理解你的问题,如果一个用户有很多项目,我认为你可以使用这个:

@user = User.create(:name=>"Bob")

# Create project and membership with user_id of @user same time, return project.
@project = @user.projects.create(:name=>"Market Survey")

如果您想找到会员,我认为还有另一种方法:

@membership = Membership.find(:first, conditions: { user_id: x, project_id: y })
于 2012-11-14T06:28:49.373 回答