Reputation: 313
I have 3 models in my Rails 3 app:
User
model:
has_many :videos, :dependent => :destroy
controller:
before_filter :signed_in_user
def show
@user = User.find(params[:id])
end
def signed_in_user
unless signed_in?
store_location
redirect_to signin_path, notice: "Please sign in."
end
end
Video
model:
belongs_to :user
has_many :surveys, :dependent => :destroy
controller:
before_filter :signed_in_user
def signed_in_user
unless signed_in?
store_location
redirect_to signin_path, notice: "Please sign in."
end
end
def show
@video = Video.find(params[:id])
@original_video = @video.panda_video
@h264_encoding = @original_video.encodings["h264"]
@surveys = Survey.all
@user = User.find(params[:id])
end
Survey
model:
belongs_to :video
controller:
before_filter :signed_in_user
def signed_in_user
unless signed_in?
store_location
redirect_to signin_path, notice: "Please sign in."
end
end
def show
@survey = Survey.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: @survey }
end
end
So in my app, a User has many Videos, and each Video has many Surveys (a.k.a. Reviews). Think of how Rotten Tomatoes works. A user has be signed in to either access a video, or write a review. Any review that user submits, while signed in, is automatically associated with that user...and this is what I'm trying to figure out with my app.
How do I associate the user id with the review? Right now, when a user is signed in, his name is automatically associated with all the reviews, whether he wrote them or not.
Upvotes: 0
Views: 152
Reputation:
You want to use your Video class as a join model via the through
option:
User
has_many :surveys, :through => :videos
Survey
has_one :user, :through => :video
This should let you do:
@user.surveys
@survey.user
Upvotes: 2
Reputation: 9700
Is there some reason this isn't as simple as:
User
has_many :surveys
Survey
belongs_to :user
If so, more info/code is required for a useful answer.
Upvotes: 0