I am currently creating a WebApp using RoR 4 and I am using has_many, though:
associations between my databases.
I have 3 models Users, UsersSubject and Subjects given below:
class UsersSubject < ActiveRecord::Base
belongs_to :users
belongs_to :subjects
end
class Subject < ActiveRecord::Base
has_many :users_subjects
has_many :users, through: :users_subjects
end
class User < ActiveRecord::Base
has_many :users_subjects, :class_name => 'UsersSubject'
has_many :subjects, through: :users_subjects
accepts_nested_attributes_for :subjects
end
I am trying to populate the UsersSubject database when I am updating the User using the User controller. Here is my from the partial form of the User:
<div class="control-group nested-fields">
<div class="contols">
<%= f.fields_for :subject do |subject| %>
<%= subject.label "Subjects" %></br>
<%= subject.collection_select(:subject_id, Subject.all, :id, :name) %>
<% end %>
</div>
</div>
and here is my controller:
def edit
user_id = current_user.id
subject_id = Subject.where(:name => params[:name])
@user_sub = UsersSubject.new(user_id: user_id, subject_id: subject_id)
@user_sub.save
end
When I do this the controller populate the UsersSubject database with the correct user_id but the subject_id is always nil
. The Subject database is already populate using the seed.rb
file.
Can someone help me understand why this is happening and help my fix it?
Thanks in advance
EDIT
Here is my development.log
Started GET "/users/edit" for ::1 at 2016-05-31 18:27:33 +0100
Processing by Users::RegistrationsController#edit as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"ZGvBq1uFUi1RxcInKFz1TnUs2ZzlZsP29aW1mzQBOVBTLm/Dq3C42cQQX0ksmBv95/qHnk08bG3f5u1v9taZgw==", "user"=>{"address"=>"", "city"=>"London", "postcode"=>"", "country"=>"United Kingdom", "subject"=>{"subject_id"=>"1"}}, "commit"=>"Update"}
Moved controller code to the update
action
def update
user_id = current_user.id
subject_id = params[:user][:subject][:subject_id] unless params[:user].nil?
@user_sub = UsersSubject.new(user_id: user_id, subject_id: subject_id)
@user_sub.save
end
Added the subject permission in the application_controller.rb
:
class ApplicationController < ActionController::Base
before_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:last_name,
:first_name, :email, :password, :current_password,
subject_attributes: [:id, :subject_id]) }
end
end
This permits the update
action to access the subject_attributes
Changes in the user
model
class User < ActiveRecord::Base
has_many :users_subjects, :class_name => 'UsersSubject', dependent: :destroy
has_many :subjects, through: :users_subjects
accepts_nested_attributes_for :subjects
end