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.
Related
I have the following models:
class Person < ApplicationRecord
has_many :interests, dependent: :destroy
accepts_nested_attributes_for :interests
validates_presence_of :email
validates_inclusion_of :gender, :in => %w(M F), message: "Gender can only be in M or F"
has_secure_password
def name
"#{first_name} #{last_name}"
end
def interests_concatenated
interests.map { |i| i.interest }.join(", ")
end
end
class Interest < ApplicationRecord
belongs_to :person
end
My controller is as follows:
class PeopleController < ApplicationController
def index
#person = Person.all
end
def new
#person = Person.new
#person.interests.build
end
def create
#person = Person.new(people_params)
if #person.save
session[:user_id] = #person.id
redirect_to(people_path)
else
flash = "Email or gender can't be blank!"
render 'new'
end
end
private
def people_params
params.require(:person).permit(:email, :first_name, :last_name, :gender, :password,:password_confirmation, interests_attributes: [:hobby])
end
end
My form is as follows:
<%= form_for #person do |f| %>
<p>
<%= f.label :email %> <br>
<%= f.text_field :email %>
</p>
<p>
<%= f.label :first_name %> <br>
<%= f.text_field :first_name %>
</p>
<p>
<%= f.label :last_name %> <br>
<%= f.text_field :last_name %>
</p>
<p>
<%= f.label :gender %> <br>
<%= f.label(:gender_male, "Male") %>
<%= f.radio_button(:gender, "M") %> <br>
<%= f.label(:gender_female, "Female") %>
<%= f.radio_button(:gender, "F") %> <br>
</p>
<p>
<%= f.label :password %> <br>
<%= f.password_field :password %>
</p>
<p>
<%= f.label :password_confirmation %> <br>
<%= f.password_field :password_confirmation %>
</p>
<p>
<%= f.fields_for :interests do |i| %>
<%= i.label :hobby %>
<%= i.text_field :hobby %>
<% end %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
Here is the byebug console log when I run it:
Very stumped why it's not working. Could it be something to do with the parameters?
Here is the log file when I submit the form:
Instead of:
#interests = #person.interests.new
try
#interests = #person.interests.build
new creates a fresh, clean, completely empty new object... but build is the special Rails association method that will fill it with appropriate defaults (like, eg the right person_id)
I found a working solution by adding this in my interests model:
class Interest < ApplicationRecord
belongs_to :person, **optional: true**
end
Since #person fails to save each time, the biggest clue was in the error message "Interest person must exist", I found this StackOverflow solution to be helpful. Also this blog post on why this is needed was helpful in shedding light on the issue.
Thanks to everyone that weighed in on it!
I am trying out for basic login and registration in ruby on rails,
ISSUE: When I click register button from new.html I am getting GET request but I can see method="post" in page source of that html
I have posted my code below
new.html.erb
<form>
<%= form_for(#user) do |f| %>
<%= f.label :user_name %>
<%= f.text_field :user_name %></br>
<%= f.label :email_id %>
<%= f.text_field :email_id %></br>
<%= f.label :password %>
<%= f.password_field :password %></br>
<%= f.label :college %>
<%= f.text_field :college %></br>
<%= f.label :major %>
<%= f.text_field :major %></br>
<%= f.label :current_job %>
<%= f.text_field :current_job %></br>
<%= f.submit("Create Account",class: "btn btn-primary") %>
<% end %>
</form>
My index.html.erb code which is loaded while application starts
<div class="container">
<div class="row">
<div class="login">
<%= form_tag("/user/login",:method => :post) do %>
<%= label_tag(:EmailId) %>
<%= text_field_tag(:email, params[:email]) %></br>
<%= label_tag(:password) %>
<%= password_field_tag(:password, params[:password]) %></br>
<%= submit_tag("Log In",class: "btn btn-primary") %>
<%= submit_tag("Register",class: "btn btn-primary") %>
<% end %>
</div>
</div>
</div>
My controller code
class UsersController < ApplicationController
def index
#user = User.all
end
def login
print "In Sign in controller"
#user = User.new
if params[:commit] == 'Register'
print "inside Register class"
redirect_to '/users/new'
else
#user = User.find(params[:email_id])
if #user and user.authenticate(params[:password])
sessions[:userId] = #user.user_id
end
end
end
def new
puts "****Inside New Method******"
#user = User.new
end
def create
puts "****Inside create Method******"
end
private
def user_params
end
end
My Route code
Rails.application.routes.draw do
root 'users#index'
resources :users
post '/users/login' => 'users#login'
As per my understanding post request should hit create method, but get /users method is hitting. Please help me out regarding this
Why do you have nested forms in new.html.erb? Remove the first form tag
<form>
<%= form_for(#user) do |f| %>
You have a form tag inside another form tag. Remove the tag at the top of your form. <%= form_for(#user) %> takes care everything that's needed to build the correct form.
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
I have the following simple rails page:
<h1> New User </h1>
<%= form_for :user, url:users_path do |f| %>
<p>
<%= f.label :email %>
<%= f.text_field :email %>
</p>
<p>
<%= f.label :password %>
<%= f.text_field :password %>
</p>
<%= f.submit %>
<% end %>
The create action gets executed and I want to access the :email attribute.
def create
render text: params[:email].inspect
end
The above always displays nil.
form_for :user will place all parameters beneath a :user key
render text: params[:user][:email].inspect
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.