Hi All,
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 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