I'm facing a challenge that I can't solve (tried multiple times and solved lots of errors but still ...)
Basically I have 3 models connected by a many-to-many through association:
class Student < ActiveRecord::Base
has_many :likes, :dependent => :destroy
has_many :recruiters, :through => :likes
accepts_nested_attributes_for :likes, :allow_destroy => true
end
class Recruiter < ActiveRecord::Base
has_many :likes
has_many :students, through: :likes
end
class Like < ActiveRecord::Base
belongs_to :student
belongs_to :recruiter
accepts_nested_attributes_for :student
end
Now students should be able to tell recruiters if they can contact the student.
the view (students/show.html.erb) <--
So each student can like multiple recruiters and each recruiter can be liked by one or more students. A like has an attribute :match wich is a boolean. When this attribute is true I want to be able to list all students who like (:match = true) a certain recruiter.
This is the form I'm using to pass the :match attribute:
<div class="show">
<%= form_for [@student,@like] do |f| %>
<%= f.fields_for :likes do |p| %>
<%= f.check_box :match %>
<%= f.hidden_field :recruiter_id, :value => '20' %>
<%end%><br>
<%= f.submit "Let them contact me!" , class:"btn btn-primary" %> <br>
<% end %>
So if a student checks the checkbox it should create a record in the database with an updated like for the current student. But that's not happening :). It only creates a NEW record only with a :student_id (so without a :recruiter_id and :match)
This is how my controllers look like:
class StudentsController < ApplicationController
def show
@student = Student.find(params[:id])
@like = Like.new
end
end
and
class LikesController < ApplicationController
before_action :find_student, only: [:new, :create, :update, :edit]
def new
end
def create
@student = Student.find(params[:student_id])
@like = @student.likes.build(like_params)
if @like.save
redirect_to student_path(@student)
else
render :show
end
end
private
def like_params
params.require(:like).permit(likes_attributes: [ :id, :match, :student_id, :recruiter_id])
end
def find_student
@student = Student.find(params[:student_id])
end
end
Anyone an idea on how to save the :recruiter_id and :match attribute to the database ?
Aucun commentaire:
Enregistrer un commentaire