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

You could do something like:

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

not sure if if it is easier/better than what your doing though.

4

3 に答える 3

3

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)

Not perfect, and requires additional code, but it does read better than your current code, and that counts for a lot in Ruby.

于 2012-11-14T07:01:02.550 に答える
0

I'm not sure if I understand your question, If one user has many projects, i think you can use this:

@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")

If you want to find a membership, i think there is another way:

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

次のようなことができます:

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

あなたがしていることよりも簡単/良いかどうかはわかりません。

于 2012-11-13T22:35:11.633 に答える