Nested Form Rails UPDATING - ruby-on-rails

I hope they are good, need to do nested forms with the profile of a user and their respective car.
each user has their own profile:
class PerfilController < ApplicationController
before_filter :authenticate_user!
def index
end
def show
#usuario = current_user
#usuario.perfil ||= Perfil.new
#perfil = #usuario.perfil
end
def update
#usuario = current_user
#perfil = #usuario.perfil
respond_to do |format|
if #usuario.perfil.update_attributes(perfil_params)
format.html {redirect_to #usuario, notice: "Datos Actualizados" }
else
format.html {render action: "show"}
end
end
end
private
def perfil_params
params.require(:perfil).permit(:nombre, :apellido, :rut)
end
end
I want the fund to ensure that each time a user posts a car, you can update your profile. Deputy nested form
<%= simple_form_for(#auto) do |f| %>
<%= f.error_notification %>
<%=f.fields_for #perfil do |perfil_builder|%>
<p>
<%= perfil_builder.label :nombre %><br/>
<%= perfil_builder.text_field :nombre %>
<%= perfil_builder.label :apellido %><br/>
<%= perfil_builder.text_field :apellido %>
<%= perfil_builder.label :rut %><br/>
<%= perfil_builder.text_field :rut %>
</p>
<%end%>
<div class="form-inputs">
<%= f.association :region %>
<%= f.association :ciudad %>
<%= f.association :marca %>
<%= f.input :modelo %>
<%= f.input :version %>
<%= f.input :año %>
<%= f.input :patente %>
<%= f.association :tipo_transmision %>
<%= f.association :combustible %>
<%= f.association :tipo_vehiculo %>
<%= f.association :carroceria %>
</div>
<div class="form-actions">
<%= f.button :submit, :id => 'submit' %>
</div>
<% end %>
The problem is when you want to update does not change the user data but if you publish the article. the error in the console is: Unpermitted parameter: perfil
Best regards friends.

You are sending the request to the auto controller, hence the Unpermitted parameter: perfil error and failure to update.
You can add this to your Perfil controller:
has_many: :autos
accept_nested_attributes_for: :autos
Then in the view switch it around like this:
<%= simple_form_for(#perfil) do |f| %>
<%= f.error_notification %>
<%= f.label :nombre %><br/>
<%= f.text_field :nombre %>
...
<%=f.fields_for :auto do |auto_builder|%>
<p>
<%= auto_builder.association :region %><br/>
...
See this page for more info: http://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html

Related

Action Controller: Exception | undefined method `fetch_value' for nil:NilClass

I am always getting this error message:
NoMethodError in ListsController#new undefined method `fetch_value' for nil:NilClass
Extracted source (around line #8):
7 def new
8 #list = List.new
9 end
I don't get the reason for this error ^^
My routes.rb
Rails.application.routes.draw do
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
root 'lists#index'
get 'home' => 'lists#index', as: 'home'
get 'new' => 'lists#new', as: 'new'
resources :lists
end
Database name:
:lists
Model name:
list
lists_controller:
class ListsController < ApplicationController
def index
#lists = List.all
end
def new
#list = List.new
end
def show
#list = List.find(params[:id])
end
def create
#list = List.new(list_params)
if(#list.save)
redirect_to #list
else
render 'new'
end
end
def edit
#list = List.find(params[:id])
end
def update
#list = List.find(params[:id])
if(#list.update(list_params))
redirect_to #list
else
render 'edit'
end
end
def destroy
#list = List.find(params[:id])
#list.destroy
redirect_to lists_path
end
private def list_params
params.require(:list).permit(:date, :class, :lesson, :subject, :teacher, :room, :info)
end
end
new.html.erb
<%= form_for :list, url: lists_path do |f| %>
<% if #list.errors.any? %>
<% #list.errors.full_messages.each do |error| %>
<div class="alert alert-danger"><%= error %></div>
<% end %>
<% end %>
<div class="alert alert-info">Please fill out all the fields below.</div>
<p>
<%= f.label :date %><br>
<%= f.text_field :date, {:class => 'form-control'} %>
</p>
<p>
<%= f.label :class %><br>
<%= f.text_area :class, {:class => 'form-control'} %>
</p>
<p>
<%= f.label :lesson %><br>
<%= f.number_field :lesson, {:class => 'form-control'} %>
</p>
<p>
<%= f.label :subject %><br>
<%= f.text_field :subject, {:class => 'form-control'} %>
</p>
<p>
<%= f.label :teacher %><br>
<%= f.text_field :teacher, {:class => 'form-control'} %>
</p>
<p>
<%= f.label :room %><br>
<%= f.text_field :room, {:class => 'form-control'} %>
</p>
<p>
<%= f.label :info %><br>
<%= f.text_area :info, {:class => 'form-control'} %>
</p>
<p>
<%= f.submit({:class => 'btn btn-info'}) %>
</p>
<% end %>
Using the BootstrapCDN and only the default gems.
Thanks for any answers :)
In your model you have an attribute named class which is a reserved keyword which is causing issues. As I can see your code:
<p>
<%= f.label :class %><br>
<%= f.text_area :class, {:class => 'form-control'} %>
</p>
So you should never use reserved keywords as attributes because you are overriding it in that case. So when overriding it, your attribute will not consist of all the properties required by the language. That is why you are getting the error.
Rails is trying to fetch the attributes from :list which should be #list
Change the form_for in new.html.erb from
<%= form_for :list, url: lists_path do |f| %>
to
<%= form_for #list, url: lists_path do |f| %>

Display fields before dynamically adding with cocoon gem

I have a form and i am using cocoon gem to add extra fields if the user requires. As it stands, its displays add educations link and then the fields appear, I would like to have the fields present in the form and then if required, users clicks add education link to render the fields. Other than that its all working fine, the models are all set up properly, but can't figure this out.
new.html.erb
<%= form_for #profile do |f| %>
<%= f.label :bio %>
<%= f.text_area :bio %>
<%= f.label :university %>
<%= f.text_field :university %> <br>
<%= f.label :course %>
<%= f.text_field :course %> <br>
<%= f.label :finishedDate %>
<%= f.text_field :finishedDate %> <br>
<div id="educations">
<%= f.fields_for :educations do |education| %>
<% render 'education_fields', f: education %>
<% end %>
<div class="links">
<%= link_to_add_association 'add education', f, :educations %>
</div>
</div>
<%= f.button :submit %>
<% end %>
_education_fields.html.erb
<div class="nested-fields">
<%= f.label :university %>
<%= f.text_field :university %> <br>
<%= f.label :course %>
<%= f.text_field :course %> <br>
<%= f.label :finishedDate %>
<%= f.text_field :finishedDate %> <br>
<%= link_to_remove_association "remove education", f %>
</div>
profiles_controller.rb
class ProfilesController < ApplicationController
def index
#profiles = Profile.all
end
def new
#profile = Profile.new
#profile = educations.build
end
def create
#profile = Profile.create(profile_params)
redirect_to profiles_path
end
def show
#profile = Profile.find(params[:id])
end
def edit
#profile = Profile.find(params[:id])
end
def update
#profile = Profile.find(params[:id])
#profile.update(profile_params)
redirect_to(profiles_path(#profile))
end
private
def profile_params
params.require(:profile).permit(:bio, educations_attributes:[:id, :university, :course, :finishedDate, :destroy])
end
end
The form shows a profile, with all it's existing educations. So if you want to show the fields for an education by default, add an education before rendering the form.
So, in your controller, where you do something like
#profile = Profile.new
you can build an initial education so it will show up in the form:
#profile = Profile.new
#profile.educations.build

Simple Form simple_fields_for only show last record

I have a nested simple form to edit a user. The user has a profile he/she can update, and a new record is written to the profile table.
simple_fields_for shows all profile records of a user due to the relationship user 1 to many profile records. However, I would like to only show the newest profile record in the form! How can I accomplish that?
<%= simple_form_for(#user) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :lang %>
<%= f.input :firstname %>
<%= f.input :lastname %>
<%= f.input :email %>
<%= f.input :born %>
<%= f.input :gender %>
<%= f.simple_fields_for :profile do |p| %> # the magic needed here
<%= p.input :postal_code %>
<%= p.input :core %>
<%= p.input :daytime %>
<%= p.input :style %>
<% end %>
<% if #is_new %>
<%= f.simple_fields_for :status do |s| %>
<%= s.input :entered, as: :hidden, input_html: { value: Time.current } %>
<% end %>
<% end %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
Little late, but accepted answer is not 100% accurate. (Would just make this a comment, but no rep.) I would do this like so:
Assuming you have
class User < ActiveRecord::Base
has_many :profiles
...
def latest_profile
profiles.order(...) # query to get whatever record it is you want
end
end
your simple_fields_for can just be
<%= f.simple_fields_for :profiles, f.object.latest_profile do |p| %>
Note the pluralization of :profiles, and that we don't need to clutter the controller with an additional instance variable because you can access the object in the form. (Using the singular will work I believe, but you will not get params with a key in the form of :profiles_attributes, meaning even more code to account for unique params.)
The edit action:
class user > ApplicationController
...
def edit
#profile = #user.profile.order("saved DESC").first
end
...
end
The working form:
<%= simple_form_for(#user) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :lang %>
<%= f.input :firstname %>
<%= f.input :lastname %>
<%= f.input :email %>
<%= f.input :born %>
<%= f.input :gender %>
<%= f.simple_fields_for :profile, #profile do |p| %> # the magic needed here
<%= p.input :postal_code %>
<%= p.input :core %>
<%= p.input :daytime %>
<%= p.input :style %>
<% end %>
<% if #is_new %>
<%= f.simple_fields_for :status do |s| %>
<%= s.input :entered, as: :hidden, input_html: { value: Time.current } %>
<% end %>
<% end %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>

Form for related model not showing up

I am trying to have a form show up for a related model, but it is not displaying when I view the page in a browser. How do I url field in my fields_for to display?
Here is my code:
User Model:
class UsersController < ApplicationController
def new
#user = User.new
#user.websites.build
end
def create
#user = User.new(params[:user])
if #user.save
redirect_to root_url, :notice => "Signed up!"
else
render "new"
end
end
end
Website Model:
class Website < ActiveRecord::Base
belongs_to :user
end
Users View:
<h1>Sign Up</h1>
<%= form_for #user do |f| %>
<% if #user.errors.any? %>
...
<% end %>
<p>
<%= f.label :email %><br/>
<%= f.text_field :email %>
</p>
<p>
<%= f.label :password %><br/>
<%= f.password_field :password %>
</p>
<p>
<%= f.label :password_confirmation %><br/>
<%= f.password_field :password_confirmation %>
</p>
<% f.fields_for :websites do |builder| %>
<%= builder.label :url %><br/>
<%= builder.text_field :url %>
<% end %>
<p class="button"><%= f.submit %></p>
<% end %>
Final output:
You missed the equals sign in your erb tag.
<% f.fields_for :websites do |builder| %>
.. should be ..
<%= f.fields_for :websites do |builder| %>
Does that fix it?
It looks like you're maybe confusing singular and plural in your fields_for as well. Calling it with the plural websites then treating the block as a singular website doesn't make sense.

rails form data not getting saved to db

I'm new to rails and trying to make a simple site to start learning. When I submit my form, however, the data isn't saved to the db. I'm really not sure what's wrong, I've been trying to figure it out for a while. If I make a record in the rails console and save it, that one successfully shows up in the db (and on the index page).
calculate.rb:
class Calculate < ActiveRecord::Base
attr_accessible :number, :root
end
calculates_controller.rb:
class CalculatesController < ApplicationController
def index
#calculate = Calculate.all
end
def new
#calculate = Calculate.new
end
def create
#calculate = Calculate.new(params[:calculate])
if #calculate.save
redirect_to '/calculates'
else
render 'new'
flash[:notice] = "Didn't work"
end
end
end
new.html.erb:
<%= form_for(#calculate) do %>
<%= label_tag(:number, "Enter the number") %>
<%= text_field_tag :number %>
<%= label_tag(:root, "root") %>
<%= text_field_tag :root %>
<%= submit_tag("Submit") %>
<% end %>
if you are using form_for, use the form_for syntax
<%= form_for(#calculate) do |form| %>
<%= form.label :number %>
<%= form.text_field :number %>
<%= form.label :root %>
<%= form.text_field :root %>
<%= form.submit "Submit" %>
<% end %>
this will automatically handle the routes if the #calculate is new object it will submit it to create or if it is already saved it will send a put request to edit action
Ah hah! I updated my view to:
<%= form_for #calculate, :url => { :action => "create" } do |f| %>
<%= f.label :number %>
<%= f.text_field :number %>
<%= f.label :root %>
<%= f.text_field :root %>
<%= submit_tag("Submit") %>
<% end %>
And now it works. Awesome.

Resources