0

I have two models in my rails app:Mem and Team. One team has many mems.

As we all know,if I just want to get the field id in team,I will write:

Team.select('id')

If I want to get the team of a mem, I will write:

Mem.find(1).team

Now I want to get the team id and name, so I write:

Mem.find(1).team.select('id,name')

I got an error.

How should I do this correctly?

HXH
  • 1,643
  • 4
  • 19
  • 31

2 Answers2

1
team = Mem.find(1).team.select('id,name')

team_id   = team.id
team_name = team.name

You may want to see this Ruby rails - select only few columns from the data base

Community
  • 1
  • 1
Yana Agun Siswanto
  • 1,932
  • 18
  • 30
0

You are confusing a SQL query with a model attribute. Team.select('id') is the first part of a query that will return the id of whatever team you are looking for. If you want to get the id of a team model, you just write team.id, so your code should be mem.team.id, where mem is a model from the Mem class and team is a model from the Team class.

Let me expound a little. You need some piece of information that is unique to your model in order to retrieve your model from the database. I am going to assume that you will be using the id, but you can use any attribute or combinations of attributes.

Let's retrieve our models from the database:

star_player = Mem.find('5')
team_id = star_player.team.id

Two queries were executed, one that retrieved your team member using find and another to retrieve the team id was performed automatically using the rails associations that you should have set up.

RustyToms
  • 7,600
  • 1
  • 27
  • 36
  • Thanks for your answer,maybe the fields is not just `id`,maybe some fields just like `name`,`dt`. – HXH Dec 12 '13 at 04:16