Nested form not saving the data - ruby-on-rails-3

I have 3 models. Firstly I have a voter which has many votes. Votes is a join table to link the voter and the entry. But when I try to save the votes they are not saving. My models look like this:
class Vote < ActiveRecord::Base
belongs_to :entry
belongs_to :voter
attr_accessible :entry, :voter, :voter_id
class Voter < ActiveRecord::Base
attr_accessible :email_address, :verification_code, :verified, :votes_attributes, :votes
has_many :votes, :class_name => "Vote"
accepts_nested_attributes_for :votes
class Entry < ActiveRecord::Base
attr_accessible :caption, :email_address, :filename
end
I am then my form looks like this:
<%= f.fields_for :votes do |builder| %>
<fieldset>
<%= builder.label :votes, "Vote" %>
<%= collection_select(:votes, :entry_id, Entry.all, :id, :caption, :prompt => 'Please select an Entry') %>
</fieldset>
<% end %>
But the votes are not saving in the database. The response looks like this:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"x5f85viIp/KHJKQF7DotaF3MhebARWcaLDKRbcZw/lM=", "voter"=>{"email_address"=>"sadasfd"}, "votes"=>{"entry_id"=>"3"}, "commit"=>"Create Voter"}
So whats going wrong?

Please try
class Voter < ActiveRecord::Base
attr_accessible :email_address, :verification_code, :verified, :votes
has_many :votes, :class_name => "Vote"
attr_accessible :votes_attributes,
accepts_nested_attributes_for :votes
Modify vote_params in VotesController
private
def vote_params
params.require(:vote).permit(:id, :email_address, :verification_code, :verified, votes_attributes: [:id, :name])
end

Related

Form not displayed correctly

i have a form consists of the following models
Employee.rb
class Employee < ActiveRecord::Base
attr_accessible :employee_number, :joining_date, :first_name, :middle_name, :last_name,
:gender, :job_title, :employee_department_id, :qualification, :experience_detail,
:experience_year, :experience_month, :status_description, :date_of_birth, :marital_status,
:children_count, :father_name, :mother_name, :husband_name, :blood_group, :nationality_id,
:home_address_line1, :home_address_line2, :home_city, :home_state, :home_pin_code,
:office_address_line1, :office_address_line2, :office_city, :office_state, :office_pin_code,
:office_phone1, :office_phone2, :mobile_phone, :home_phone, :email, :fax, :user_id,
:reporting_manager_id, :employee_grade_id, :office_country_id,
:home_country_id, :employee_category, :employee_position_id
belongs_to :employee_department
has_many :counselor_supervisors
belongs_to :employee_position
def to_label
full_name = first_name + " " + last_name
end
end
EmployeeDepartment.rb
class EmployeeDepartment < ActiveRecord::Base
attr_accessible :code, :name
has_many :employees
has_many :employee_positions
has_many :counselor_supervisors
has_many :batch_leadership_supervisors
def to_label
name
end
end
CounselorSupervisor.rb
class CounselorSupervisor < ActiveRecord::Base
attr_accessible :employee_id, :employee_department_id, :employee_position_id
belongs_to :employee
belongs_to :employee_department
has_many :batch_counselor_supervisors
def to_label
employee.to_label
end
end
BatchCounselorSupervisor.rb
class BatchCounselorSupervisor < ActiveRecord::Base
attr_accessible :counselor_supervisor_id , :employee_department_id , :counselor_batch_id,
:batch_counselor_advisors_attributes
has_many :batch_counselor_advisors
belongs_to :counselor_supervisor
belongs_to :employee_department
belongs_to :counselor_batch
accepts_nested_attributes_for :batch_counselor_advisors
end
Employee_position.rb
class EmployeePosition < ActiveRecord::Base
attr_accessible :position_title, :employee_department_id
has_many :employees
belongs_to :employee_department
def to_label
position_title
end
end
batch_counselor_supervisors/new.html.erb (part of the form which related to my question)
<%= simple_form_for(#batch_counselor_supervisor) do |f| %>
<%= f.error_messages %>
<%= f.association :employee_department, as: :select %>
<%= f.input :counselor_supervisor_id , collection: EmployeeDepartment.all, as: :grouped_select, group_method: :counselor_supervisors %>
<% end %>
the dropdown list appears like this:
If I added an employee which belongs to the first department "Business Administration", the form will be displayed correctly like this:
Update: after adding label_method: :to_label, so my form became like this :
<%= simple_form_for(#batch_counselor_supervisor) do |f| %>
<%= f.error_messages %>
<%= f.association :employee_department, as: :select %>
<%= f.input :counselor_supervisor_id ,
collection: EmployeeDepartment.all, as: :grouped_select, group_method: :counselor_supervisors, label_method: :to_label %>
<% end %>
the employee name displayed correctly but still the department name not displayed correctly as the following image:
Is this SQLite3 issue ? and What can I do in order to solve this if it sqlite3 issue or not.
From what I see, you only have an issue with the labels not being displayed correctly. Could you try to explicitly set the method on your input:
label_method: :to_label
For more information have a look at https://github.com/plataformatec/simple_form and search for *label_method*
What are the actual relevant rows in your Employee table and your EmployeePosition table?
In your Employee table you happen to have these 2 columns;
employee_position_id
employee_position.
Since employee_position is also a table name, it's bad/reduntant model structure which might be confusing your include method of the query. It's possible that in your tables, the rows are fully filled out to complete the first query, but not for any of your other queries even though you think it is.

Rails 3 my first nested form doesnt work - Can't mass-assign protected attributes

I'm creating my first nested form in Rails 3.2.13. User is registering and he fill email, password and address information and company information.. but the error is showing while user click on submit. Error is at the bottom.
Im not sure about this line: attr_accessible :address_attributes, :company_attributes
which i read it could help but it doesnt and i have addresses in the view but address in the model because of one-to-one relationship but if i have <%= f.fields_for :**address** do |builder| %> the form doesnt show up.
Please what i have to do ? :-)
The post sends then
"companies"=>{"name"=>"Companyname"
User model
class User < ActiveRecord::Base
attr_accessible ...
has_many :orders
belongs_to :address
belongs_to :company
accepts_nested_attributes_for :address, :company
attr_accessible :address_attributes, :company_attributes
Company model
class Company < ActiveRecord::Base
attr_accessible ...
has_many :users
validates_presence_of ...
end
Address model
class Address < ActiveRecord::Base
attr_accessible ...
has_many :orders, :foreign_key => 'payment_address_id'
has_many :orders, :foreign_key => 'delivery_address_id'
has_many :users
validates_presence_of ...
end
new.html.erb (creating new user)
<%= form_for #user do |f| %>
...
<%= f.fields_for :addresses do |builder| %>
...
<% end %>
<%= f.fields_for :companies do |builder| %>
...
<% end %>
<%= f.submit %>
<% end %>
error while i click on submit
Can't mass-assign protected attributes: addresses, companies
EDIT:
First mistake: i changed in Class User
belongs_to :address
belongs_to :company
on
has_one :address
has_one :company
and in Address and Company model i edit
has_many :users
on
belongs_to :user
but nested forms doesnt show up in the view.. i tried edit Users Controller by adding .build method
def new
#user = User.new
#user.company.build
#user.address.build
end
but im getting new error
undefined method `build' for nil:NilClass
please what i have to do now ?
I had a case like this a day ago, and that's what I used.
class User
attr_accessible :name, :email, :company_attributes, :address_attributes
has_one :company
accepts_nested_attributes_for :company
end
and EmailSetting:
class Company
belongs_to :user
end
after this I can run in console:
User.new.build_company
as for form:
<%= form_for #user do |f| %>
<%= f.fields_for :company do |builder| %>
<%= f.text_field :name %>
<% end %>
<% end %>
in controller you just initialize the #user variable, no need to do #user.company.build or #user.address.build

jQuery TokenInput plugin with deep nested_attributes pre-populating tokens on edit

I have the following structure working on my application.
class Foo < ActiveRecord::Base
has_many :examples, :dependent => :destroy
accepts_nested_attributes_for :examples
end
class Example < ActiveRecord::Base
belongs_to :foo
has_many :codes, :dependent => :destroy
accepts_nested_attributes_for :codes, :reject_if => lambda { |a| a[:code].blank? }
end
class Code < ActiveRecord::Base
belongs_to :example
has_many :code_kinds
has_many :kinds, :through => :code_kinds
attr_reader :kind_tokens
def kind_tokens=(ids)
self.kind_ids = ids.split(",")
end
end
class CodeKind < ActiveRecord::Base
belongs_to :code
belongs_to :kind
end
class Kind < ActiveRecord::Base
has_many :code_kinds
has_many :codes, :through => :code_kinds
end
And it's working perfectly for the form with fields_for on create and save.
I'm using kind_tokens as described on RailsCast #258 Token Fields
But on the edit form everything displays perfectly now I should be pre-populating the data in a data-pre attribute on the kind_tokens field inside the nested attributes for code in examples.
The RailsCast say:
<%= f.text_field :author_tokens, "data-pre" => #book.authors.map(&:attributes).to_json %>
But I can't do #foo.examples.codes.kinds.map... because the relation with Foo and examples returns a collection, the same situation with codes.
I'm just using:
<%= f.fields_for :codes do |codes_form| %>
That's inside of
<%= f.fields_for :examples do |examples_form| %>
Now how can I pre-populate the kind for code if I don't have any loop, and everything's done by nested_attributes and fields_for ?
Solved
Everytime you use a
<%= f.fields_for ...
Rails automatically makes a loop so you can have some kind of counter there like:
<%
#ctrEx = 0
#ctrCd = 0
%>
<%= form_for #foo ...
<%= f.fields_for :examples do |examples_form| %>
...
<%= examples_form.fields_for :codes do |codes_form| %>
...
<%= codes_form.text_field :kind_tokens, :class => "tag_matcher", "data-pre" => #foo.examples[#ctrEx].codes[#ctrCd].kinds.map(&:attributes).to_json %>
...
<%#ctrCd +=1%>
<%end%>
...
<%
#ctrEx += 1
#ctrCd = 0
%>
<%end%>
<%end%>
Now you can use your counters in the data-pre like this:
#foo.examples[#ctrEx].codes[#ctrCd].kinds.map(&:attributes).to_json
That's the way i figured it out, but there must be another way.

Possible to chain queries in Rails 3?

I have something like the following
class Group < ActiveRecord::Base
has_many :group_users
end
class GroupUser < ActiveRecord::Base
belongs_to :user, :group
end
class User < ActiveRecord::Base
has_many :group_users
end
The reason I'm not using has_many_through is because the group_user class has more information than just a link table, so I want to be able to access those values.
What I would like to do though is pass #groups to the page and loop through the group users but get at the user object as well
so
<% #groups.each do |group| %>
<%= group.group_user.user.name %>
<% end %>
Here is how I would do it:
User Model
class User < ActiveRecord::Base
has_many :memberships
has_many :groups, :through => :memberships
end
Group Model
class Group < ActiveRecord::Base
has_many :memberships
has_many :users, :through => :memberships
end
Membership Model
class Membership < ActiveRecord::Base
belongs_to :user
belongs_to :group
end
Controller
def show
#groups = Group.all
end
View
<% #groups.each do |group| %>
<% group.users.each do |user| %>
<%= user.name %>
<% end %>
<% end %>
There are probably a few ways to do it, but this should get you started.
Hope this helps!
If you want to access attributes from the GroupUser model, just do this:
<% #groups.each do |group| %>
<% group.group_users.each do |group_user| %>
<%= group_user.attribute_name %>
<%= group_user.user.name
<% end %>
<% end %>
To make this more efficient from the SQL side of things you can use eager loading:
Group.all(:includes => [:group_users => :user])
F

Rails many to one association - Help showing many in one view

These are my models:
class Bedommelse < ActiveRecord::Base belongs_to :virksomhed_primary,
:class_name => 'Virksomhed',
:foreign_key => 'virksomhed_id' belongs_to :virksomheds,
:foreign_key => "virksomhed_id"
end
class Bedommelse < ActiveRecord::Base belongs_to :virksomheds,
:foreign_key => "virksomhed_id" belongs_to :freelances,
:foreign_key => "freelance_id"
end
I am trying to display the name of the virksomhed_id not the id itself in the One View (Bedommelse view)
I can show the column virksomhed_id:
<% #bedommelses.each do |bedommelse| %>
<p><%= bedommelse.virksomhed_id</p>
<% end %>
How do I show the name of the virksomhed?
I have tried this but it didn't work.
<% #bedommelses.each do |bedommelse| %>
<p><%= bedommelse.virksomhed.navn </p>
<% end %>
I have found my mistake
I did a fail in the models:
It should be:
belongs_to :virksomhed
not
belongs_to :virksomheds
And the view should be:
<%= #bedommelse.virksomhed.navn %>