Rails Nested Form - Filter by Current User, Lesson-Questions-Answers-Users
I have a nested form that is based on the following model -- A lesson has many questions, each question has many answers, and answers belong to users.
I am developing a nested form, so that a new user can review the questions and post answers. If a user has entered answers in the past, I want those to show up; otherwise show blank fields. I also don't want the user to see anyone else's answers.
So, I can't figure 开发者_StackOverflow中文版out how to show only the answers for the currently logged-in user. I created a named_scope, but it doesn't work(see my edit action). Right now, when editing, I see the answers for all users underneath each question. To build the view I followed the nested form example from Railscast 196.
Thank you for your help. Here is the code showing my models and the lessons controller.
class Lesson < ActiveRecord::Base
has_many :questions, :dependent => :destroy
accepts_nested_attributes_for :questions, :allow_destroy => true,
:reject_if => proc { |a| a['data'].blank? }
end
class Question < ActiveRecord::Base
belongs_to :lesson
has_many :answers
accepts_nested_attributes_for :answers,
:reject_if => lambda { |a| a['data'].blank? }, :allow_destroy => true
end
class Answer < ActiveRecord::Base
belongs_to :question
belongs_to :user
named_scope :by_user,
lambda {|user| {:conditions => ["user_id = ?", user]}}
end
class User < ActiveRecord::Base
has_many :answers
accepts_nested_attributes_for :answers,
:reject_if => lambda { |a| a['name'].blank? }, :allow_destroy => true
end
LESSONS Controller:
def edit
@lesson = Lesson.find(params[:id])
if current_user_admin == 99 # show blank question field if admin user
@questions = @lesson.questions.build(:user_id => current_user)
end
@lesson.questions.each do |question|
# if there are no answers for this user
if question.answers.by_user(current_user.id).size != 1
# if the current user is not admin
if current_user_admin != 99
question.answers.by_user(current_user.id).build(:user => current_user)
end
end
end
end
That named scope looks like it should work to me. Are you sure that the answer records in your database have a user_id
set properly?
I think that the hash you get in the reject_if
lambda has keys that are strings rather than symbols so your nested models fields may be silently getting rejected.
Iv spotted a problem with the code in your controller. You are building an answer object inside the each block which iterates through answers, only if that answer is nil, which will never happen.
I think your what you are trying to do in your controller is something like:
def edit
@lesson = Lesson.find(params[:id])
@lesson.questions.each do |question|
if question.answers.by_user(current_user.id).empty?
question.answers.build(:user => current_user)
end
end
end
精彩评论