Hello i have problem with nested form.. im looking an hour to that and dont know what i forget ..
models/trainer.rb
class Trainer < ActiveRecord::Base
attr_accessible :telephone, :user_attributes
has_one :user
accepts_nested_attributes_for :user
end
models/user.rb
class User < ActiveRecord::Base
belongs_to :trainer
attr_accessible :email, :image_url, :name, :password_hash, :password_salt, ...
attr_accessible :password, :password_confirmation
attr_accessor :password
before_save :encrypt_password
<+ validations ...>
controllers/trainers_controller.rb
def new
#trainer = Trainer.new
#trainer.build_user
respond_to do |format|
format.html # new.html.erb
format.json { render json: #trainer }
end
end
and i can display new trainer form view (i addedd all user columns as nested)
but when i hit CREATE i get
Can't mass-assign protected attributes: user
whats wrong ? thank you
edit: my db schema looks like
[users]
id
trainer_id
name
surname
[trainers]
telephone
Here i uploaded my simplify simple app if anyone was interested :)
https://github.com/ScottHiscock/NestedForm
Ref accepts_nested_attributes_for
Defines an attributes writer for the specified association(s).
If you are using attr_protected or attr_accessible, then you will need to add
the attribute writer to the allowed list.
So I think you have to do the following:
class Trainer < ActiveRecord::Base
attr_accessible :telephone, :user_attributes
Also add user to attr_accessible list of trainer.rb model as follows
attr_accessible :telephone, :user_attributes
or try this
attr_accessible :telephone, :user
the mistake was in the view, i had
<%= f.fields_for :users do |u| %>
but correct is
<%= f.fields_for :user do |u| %>
:-)
Related
I'm following the docs and toying with simple_form, formtastic, and nested_form gems with no success. This very simple example yields empty for for me:
resort.rb
class Resort < ActiveRecord::Base
attr_accessible :address, :description, :latitude, :longitude, :name, :phone, :second_name,
:resort_type_id, :infrastructure_attributes
validates_presence_of :name, :address, :phone, :description
has_many :infrastructures
belongs_to :resort_type
accepts_nested_attributes_for :infrastructures
end
infrastructure.rb
class Infrastructure < ActiveRecord::Base
attr_accessible :name, :description, :infrastructure_type_id, :resort_id
belongs_to :resort
belongs_to :infrastructure_type
end
form view
= form_for #resort do |f|
= f.fields_for :infrastructures do |i|
= i.text_field :name
Seems I missed something obvious but can't figure out what exactly is wrong with the code.
If I may ask, in your controller action did you build the appropriate code for your infrastructure. Something like
3.times { #resort = #resort.infrastrucures.build }
To my knowledge you need something like this for your form before it can build the proper nested form content
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
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
I am getting a "NoMethodError in ProjectsController#create" with the following code:
def create
#project = current_user.project.build(params[:project])
if #project.save
flash[:success] = "Project created!"
redirect_to root_url
end
end
I have tried using #project = current_user.project.create(params[:project]) as well, but I get the same error, albeit for .create.
My Project model looks like this:
class Project < ActiveRecord::Base
attr_accessible :title,
:sub_title,
:desc,
:category
validates :user_id, presence: true
validates :title, presence: true, length: { maximum: 35 }
validates :category, presence: true
belongs_to :user
...
end
and my User model looks like this:
class User < ActiveRecord::Base
attr_accessible :name,
:surname,
:email,
:email_confirmation,
:password,
:password_confirmation
has_secure_password
has_one :project
...
end
From what I can tell, this should create a new Project with an association to the user.id and project.user_id. Any ideas why I get the error instead of successful creation?
For has_one associations you want:
#project = current_user.build_project(params[:project])
The same pattern is used for create:
#project = current_user.create_project(params[:project])
If you look at the has_one documentation they list the methods that get created when you declare the association.
I have been getting all kinds of conflicting information regarding this basic question, and the answer is pretty crucial to my current problems. So, very simply, in Rails 3, is it allowed or not allowed to use accepts_nested_attributes_for with a belongs_to relationship?
class User < ActiveRecord::Base
belongs_to :organization
accepts_nested_attributes_for :organization
end
class Organization < ActiveRecord::Base
has_many :users
end
In a view:
= form_for #user do |f|
f.label :name, "Name"
f.input :name
= f.fields_for :organization do |o|
o.label :city, "City"
o.input :city
f.submit "Submit"
Nested attributes appear to work fine for a belongs_to association as of Rails 4. It might have been changed in an earlier version of Rails, but I tested in 4.0.4 and it definitely works as expected.
The doc epochwolf cited states in the first line "Nested attributes allow you to save attributes on associated records through the parent." (my emphasis).
You might be interested in this other SO question which is along the same lines as this one. It describes two possible solutions: 1) moving the accepts_nested_attributes to the other side of the relationship (in this case, Organization), or 2) using the build method to build the Organization in the User before rendering the form.
I also found a gist that describes a potential solution for using accepts_nested_attributes with a belongs_to relationship if you're willing to deal with a little extra code. This uses the build method as well.
For belongs_to association in Rails 3.2, nested model needs the following two steps:
(1) Add new attr_accessible to your child-model (User model).
accepts_nested_attributes_for :organization
attr_accessible :organization_attributes
(2) Add #user.build_organization to your child-controller (User controller) in order to create column organization.
def new
#user = User.new
#user.build_organization
end
For Ruby on Rails 5.2.1
class User < ActiveRecord::Base
belongs_to :organization
accepts_nested_attributes_for :organization
end
class Organization < ActiveRecord::Base
has_many :users
end
Just got to your controller, suppose to be "users_controller.rb":
Class UsersController < ApplicationController
def new
#user = User.new
#user.build_organization
end
end
And the view just as Nick did:
= form_for #user do |f|
f.label :name, "Name"
f.input :name
= f.fields_for :organization do |o|
o.label :city, "City"
o.input :city
f.submit "Submit"
At end we see that #user3551164 have already solved, but now (Ruby on Rails 5.2.1) we don't need the attr_accessible :organization_attributes