views:

458

answers:

4

Hi,

I have the following Rails definition:

Class Book string title has_many readings has_many users, :through => :readings

Class Reader int rating belongs_to :book belongs_to :user

Class User has_many readings has_many books, through => :readings

No I want to query like this:

Give me all readings ratings for user A that have book.title = "test"

Could you help me? Thanks!

A: 

This will give you an array of all ratings for a book with title "test" which was read by user with name "A"

User.find_by_name("A").books.find_by_title("test").readings.map{|r| r.rating }

But to be honest, I'm really not sure if this is what you want.

Milan Novota
A: 

Hi,

thanks. Looks good. I try to explian an little bit better:

The problem is that I want to build something like a generic system:

User

-id

Anwsers with EXTRA atrribute -> "answer" it contains the answer

-userID

-questionID

-anwser

Questions

-questionID

So I store the answer to a question in answers to build a generic questions.

No I want to query for e.g. "FavoriteBook" for user XY.

And of course I want to build a form where the user could answer his questions.

Could you help me to find the best rails model and the best form_for ?

Thanks!

Christian
+1  A: 

You can include the related models and use these as parameters.

Users.find(
  :all,
  :include => {:readings => :books},
  :conditions => "books.title = ? AND etc"
)

Obviously not 100% correct, but should give you the right idea.

Toby Hede
A: 

Ok,

but could you help me to find a good model for this:

I want to have a nice model that is able to build up this: (self is type of user)

self.answers.firstname

and I want to use form_for to build a form that the user is able to answer questions.

So my question is: Where to put the custom attributes? Because answers is a collection. I think this would be the wrong place...

Thanks!

Christian