Reputation: 449
I have two classes Address
and Review
. A review has an address, and an address can have many reviews. I have modeled this by saying Review belongs_to Address
and that Address has_many Reviews
.
In the application the main use case is to create a new review. As part of creating a review the user will enter an address, which behind the scenes we try to match against an existing record, or create a new one if necessary.
I have set up routing like this: resources :addresses, only: [:new, :create, :show, :update], :as => :reviews, :path => :reviews, :controller => :reviews
.
Which enables me to have URLs like /reviews/[:id]
.
What is the best way to load the address and single associated review with id=[:id].
So far I have
@review = Review.find(params[:id])
@address = @review.address
But if I then do something like
@address.reviews
I believe ActiveRecord will load all of the associated Reviews which is not what I want as I am thinking of the Review as the main entity, which has an address as part of it.
Have I muddled up my design? Conceptually an address is part of a review
but I can't see any way of modelling this such that an address can still have many review
'
EDIT:
I think some of my confusion comes from the fact that my views have forms which need to take an Address, because Address has accepts_nested_attributes_for :reviews
which makes all the validation and form building easier.
Many thanks in advance!
Upvotes: 0
Views: 213
Reputation: 172
You already have modelled it correctly imho.
For your form you most likely want something like the following:
= form_for @review do |f|
= f.body
= f.fields_for :address do |af|
= af.street
= af.city
and then in your review model you want: accepts_nested_attributes_for :address
Upvotes: 1