HXH
HXH

Reputation: 1663

Rails get the specify fields of a Model

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?

Upvotes: 0

Views: 645

Answers (2)

Yana Agun Siswanto
Yana Agun Siswanto

Reputation: 2032

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

Upvotes: 1

RustyToms
RustyToms

Reputation: 7810

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.

Upvotes: 0

Related Questions