ruby on rails - exists? returns true in the console, but not in my controller -
i'm trying have create action finds lesson date , school_id. if no lesson exists parameters, create new lesson. reason i'm not using find_by_or_create, or similar method, because want add goals of lesson if exists, nor overwrite it.
here's controller, believe that's that's relevant:
the exists? call never returning true, though when run rails console , type console same parameters, returns true. same find_by
def create find_or_create_lesson if @lesson.save flash[:success] = "response logged" redirect_to @lesson else @user = current_user @school_options = school.all.map { |s| [s.name, s.id] } render 'new' end end private # strong params def lesson_params params.require(:lesson).permit(:school_id, :date, goals_attributes: [:id, :user_id, :text, :lesson_id]) end # finds lesson same date , school, or creates lesson def find_or_create_lesson search_params = { date: lesson_params[:date], school_id: lesson_params[:school_id] } if lesson.exists?(search_params) @lesson = lesson.find_by(search_params) @lesson.goals << goal.new(goals) @lesson.assign_attributes(search_params) else @lesson = lesson.new(lesson_params) end end
what's going on?
rails has several finder methods find_or_initialize_by
, find_or_create_by
make simpler work cases dealing record may or may not persisted.
@lesson = lesson.find_or_initialize_by( date: lesson_params[:date], school: lesson_params[:school_id] )
edited.
to integrate in app do:
def create @lesson = lesson.find_or_initialize_by( date: lesson_params[:date], school: lesson_params[:school_id] ) @lesson.assign_attributes(lesson_params) if @lesson.save flash[:success] = "response logged" redirect_to @lesson else @user = current_user @school_options = school.all.map { |s| [s.name, s.id] } # can refactored out render 'new' end end private # strong params def lesson_params # want assign goals_attributes params.require(:lesson).permit(goals_attributes: [:id, :user_id, :text, :lesson_id]) end
on side note:
rails has collection_select
helper method create select tag options collection, there no need manually create array of options school.all.map { |s| [s.name, s.id] }
.
<%= f.collection_select(:school_id, school.all, :id, :name) %>
added.
if want ensure 2 lessons cannot created on same date school should add uniqueness constraint.
create db index migration database enforces rule. (to avoid race conditions)
# db/migrations/add_index_to... class addindexschooldateindextolessons def change add_index :lessons, [:date, :school_id], unique: true end end
add model validation give user feedback.
class lesson < activerecord::base # ... validates : date, uniqueness: { scope: :school_id } end
Comments
Post a Comment