I made an authentication model from scratch.
I want to associate one model (aula) with Students, I am using jquery-tokeninput do to so. But, i'm using Students as user to authenticate.
The problem is that for some reason, when I am logged in, the token gives me an error when saving.
prohibited this aula from being saved:
Seem like Aula can only save if I put the student I am logged with.
Any sugestions?
Here is the jquery:
jQuery ->
$('#aula_student_tokens').tokenInput('/students.json', {
theme: 'facebook'
prePopulate: $('#aula_student_tokens').data('load')
preventDuplicates: true
});
The create action:
def create
@aula = Aula.new(params[:aula])
respond_to do |format|
if @aula.save
format.html { redirect_to @aula, notice: 'Aula was successfully created.' }
format.json { render json: @aula, status: :created, location: @aula }
else
format.html { render action: "new" }
format.json { render json: @aula.errors, status: :unprocessable_entity }
end
end
end
Aulas model
class Aula < ActiveRecord::Base
attr_accessible :name, :student_tokens
has_many :grades
has_many :students, :through => :grades, dependent: :destroy
attr_reader :student_tokens
def student_tokens=(tokens)
self.student_ids = Student.ids_from_tokens(tokens)
end
Students model
class Student < ActiveRecord::Base
attr_accessible :name, :password, :password_confirmation, :email
has_many :grades
has_many :aulas, :through => :grades
has_secure_password
validates_uniqueness_of :email, :name
def self.tokens(query)
students = where("name like ?", "%#{query}%")
if students.empty?
[{id: "<<<#{query}>>>", name: "New: \"#{query}\""}]
else
students
end
end
def self.ids_from_tokens(tokens)
tokens.gsub!(/<<<(.+?)>>>/) { create!(name: $1).id }
tokens.split(',')
end
end
Grades model
class Grade < ActiveRecord::Base
attr_accessible :grammar, :oral, :participation, :writing
belongs_to :aula
belongs_to :student
end
Aula _form
<%= form_for(@aula) do |f| %>
<% if @aula.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(@aula.errors.count, "error") %> prohibited this aula from being saved:</h2>
<ul>
<% @aula.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :student_tokens, "Students" %><br />
<%= f.text_field :student_tokens, data: {load: @aula.students} %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Sessions Controller
class SessionsController < ApplicationController
def new
end
def create
student = Student.find_by_email(params[:email])
if student && student.authenticate(params[:password])
session[:student_id] = student.id
redirect_to root_url, notice: "Logged in!"
else
flash.now.alert = "Emails or password is invalid"
render "new"
end
end
def destroy
session[:student_id] = nil
redirect_to login_path, notice: "Logged out!"
end
end