Linking 3 Models with has_many relationships

Hello, i’ve been searching for a solution to a problem i’ve come
across and have not been able to find it yet. I’m working on a
website that returns the closest delivery restaurants to you based on
your location. I’ve completed this but i’ve begun adding a review
process to the websites. My problem right now is trying to link the
users, reviews, and restaurants models together.

Right now the relationship i’ve drawn up is

Restaurant - has_many :reviews
User - has_many :reviews
Review- belongs_to :user
belongs_to :restaurant

Now this has got me far enough to be able to link them. Showing the
reviews for a restaurant on a restaurant show page, and showing all
of the reviews of a user on a type of control panel page. However i
don’t think i implemented this correctly, because i am not able to
destroy a review and have it be removed from both the restaurant and
the user.

def create
@review = @restaurant.reviews.build(params[:review])
@user_review = current_user.reviews.build(params[:review])
if (@review.save && @user_review.save)
redirect_to restaurant_path(@restaurant)
else
render :action => “new”
end
end

this creates two separate reviews, one for each model. fields for a
review are::

r = Review.find(114)
=> #<Review id: 114, user_id: nil, restaurant_id: 5, title: “pizza”,
body: “fdsafds”, rating: 4, created_at: “2010-02-23 05:06:18”,
updated_at: “2010-02-23 05:06:18”>

I need to have a single entry contain both my user_id and
restaurant_id but i’m not sure how to accomplish this. I’ve been
reading about multi-model forms, has_many :through, and a bunch of
different plugins but i cant seem to relate it to my problem. Any
help is greatly appreciated, thanks!

However i don’t think i implemented this correctly
You only need to add a slight modification to the create action so that
the same review is connected to both the user and the restaurant:

@review = @restaurant.reviews.build(params[:review])
@review.user_id = current_user.id #hooks this review up to current_user
if (@review.save)
#(…)

Fixed code:

def create
@review = @restaurant.reviews.build(params[:review])
@review.user = current_user # FIXED HERE
if (@review.save) # AND HERE
redirect_to restaurant_path(@restaurant)
else
render :action => “new”
end
end

this creates two separate reviews, one for each model. fields for a

review are:

It will do, you were building two reviews and then saving them both.
You
should create one and then save it.

Cheers,

Andy

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs