I give up. I'm trying to build a simple nested form with 2 models following Railscasts #196 episode and doesn't work. Can someone send a working example please so I can test on my environment. I'm using 3.1.0
For example when I try to build 3 questions on the form only 1 question field appears, then survey_id is never passed across.
I would appreciate your help after 2 days and nights on it. I got missing something really big. Thanks
Model
class Survey < ActiveRecord::Base
has_many :questions, :dependent => :destroy
accepts_nested_attributes_for :questions
attr_accessible :name, :questions_attributes
end
class Question < ActiveRecord::Base
belongs_to :survey
attr_accessible :survey_id, :name
end
Controller
def new
#survey = Survey.new
4.times { #survey.questions.build }
respond_to do |format|
format.html # new.html.erb
format.json { render json: #survey }
end
end
def create
#survey = Survey.new(params[:survey])
respond_to do |format|
if #survey.save
format.html { redirect_to #survey, notice: 'Survey was successfully created.' }
format.json { render json: #survey, status: :created, location: #survey }
else
format.html { render action: "new" }
format.json { render json: #survey.errors, status: :unprocessable_entity }
end
end
end
View
<%= form_for(#survey) do |f| %>
<% if #survey.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#survey.errors.count, "error") %> prohibited this survey from being saved:</h2>
<ul>
<% #survey.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<%= fields_for :questions do |builder| %>
<%= builder.label :name, "Question" %>
<%= builder.text_field :name %>
<% end %>
<br /><br />
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Related
I am new to Rails and was creating a demo web shop app for study.
I could create the products smoothly, both via rails console and by the url localhost:300/products/new.
My problem is when I want to update them.
I have _form.html.erb partial getting rendered both in new.html.erb and edit.html.erb
In /products/id/edit though the button "Update Product" is actually destroying the product instead of updating it
This is the _form.htlm.erb:
<%= form_for(#product) do |f| %>
<% if #product.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#product.errors.count, "error") %> prohibited this product from being saved:</h2>
<ul>
<% #product.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="row">
<div class="col-sm-4 col-xs-12">
<div class="field">
<%= f.label :name %><br>
<%= f.text_field :name, :class => "input-group input-group-sm" %>
</div>
<div class="field">
<%= f.label :description %><br>
<%= f.text_area :description %>
</div>
<div class="field">
<%= f.label :image_url %><br>
<%= f.text_field :image_url %>
</div>
<div class="field">
<%= f.label :color %><br>
<%= f.text_field :color %>
</div>
<div class="actions">
<%= f.submit %>
</div>
</div>
</div>
Please tell me if you need more data
Thanks,
Anna
Updat: here below my routes.rb
Rails.application.routes.draw do
resources :products
get 'news/index' => 'news#index', as: :news
get 'store' => 'store#index', as: :store
get 'contact' => 'contact#index', as: :contact
get 'products/edit' => 'products#edit'
get 'products/destroy' => 'products#destroy'
get 'about' => 'about#index', as: :about
get 'landing_page' => 'static_pages#landing_page', as: :landing_page
get 'home/index'
root 'static_pages#landing_page'
resources :orders, only: [:index, :show, :create, :destroy]
I have pryed in the products_controller and found this:
# GET /products/1
# GET /products/1.json
def show
end
# GET /products/new
def new
#product = Product.new
end
# GET /products/1/edit
def edit
end
# POST /products
# POST /products.json
def create
#product = Product.new(product_params)
respond_to do |format|
if #product.save
format.html { redirect_to #product, notice: 'Product was successfully created.' }
format.json { render :show, status: :created, location: #product }
else
format.html { render :new }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /products/1
# PATCH/PUT /products/1.json
def update
respond_to do |format|
if #product.update(product_params)
format.html { redirect_to #product, notice: 'Product was successfully updated.' }
format.json { render :show, status: :ok, location: #product }
else
format.html { render :edit }
format.json { render json: #product.errors, status: :unprocessable_entity }
end
end
end
# DELETE /products/1
# DELETE /products/1.json
def destroy
#product.destroy
respond_to do |format|
format.html { redirect_to products_url, notice: 'Product was successfully destroyed.' }
format.json { head :no_content }
end
end
The Edit.html.erb had also three options for: Show|Delete|Back The Delete option was coded with : <%= link_to 'Delete', #product.destroy %> I deleted this line and the product got edited instead of being cancelled.
I am trying to set up in rails 3.2.0 with ruby 1.9.3 a
has_and_belongs_to_many relationship between two tables I have the proper join table migration set up with both foreign keys and my models are as such
student.rb
class Student < ActiveRecord::Base
attr_accessible :birthday, :id, :name, :year, :course_ids
has_and_belongs_to_many :courses
accepts_nested_attributes_for :courses
end
course.rb
class Course < ActiveRecord::Base
attr_accessible :id, :coursePrefix, :roomNumber, :name, :student_ids
has_and_belongs_to_many :students
end
_form.html.erb
<%= form_for(#student) do |f| %>
<% if #student.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#student.errors.count, "error") %> prohibited this student from being saved:</h2>
<ul>
<% #student.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :id %><br />
<%= f.text_field :id %>
</div>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="field">
<%= f.label :birthday %><br />
<%= f.date_select :birthday, :start_year => 1930 %>
</div>
<div class="field">
<%= f.label :year %><br />
<%= f.text_field :year %>
</div>
<div>
<%= f.collection_select(:courses, #courses, :id, :name)%>
</div>
<br />
<div class="actions">
<%= f.submit %>
</div>
<% end %>
and student_controller.rb
# GET /students/new
# GET /students/new.json
def new
#student = Student.new
#courses = Course.all
respond_to do |format|
format.html # new.html.erb
format.json { render json: #student }
end
end
# GET /students/1/edit
def edit
#student = Student.find(params[:id])
#courses = Course.all
end
# POST /students
# POST /students.json
def create
#student = Student.new(params[:student])
respond_to do |format|
if #student.save
format.html { redirect_to #student, notice: 'Student was successfully created.' }
format.json { render json: #student, status: :created, location: #student }
else
format.html { render action: "new" }
format.json { render json: #student.errors, status: :unprocessable_entity }
end
end
end
# PUT /students/1
# PUT /students/1.json
def update
#student = Student.find(params[:id])
#courses = #student.courses.find(:all)
respond_to do |format|
if #student.update_attributes(params[:student])
format.html { redirect_to #student, notice: 'Student was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #student.errors, status: :unprocessable_entity }
end
end
end
Again I am trying to get the form element to allow a student to select a course and be saved in that table under the JOIN method, however everytime I try to look for help I get different errors and cannot find a solution
Thank you for your help
You just have to give access to the :courses attribute of the Student model:
class Student < ActiveRecord::Base
attr_accessible :birthday, :id, :name, :year, :course_ids, :courses
# ^ ^ ^ ^
Why? Because your controller receive params formatted like this:
params = {
student: {
id: 12,
name: "Bob the Sponge",
courses: [5, 7], # Course ids
etc: ...
}
}
And the controller is trying to create a Student object directly with the params, so when he is trying to update the courses attribute of the Student, it can't because you didn't define it as accessible.
I have spent a while trying and searching for answers to debug this.
I am following Railscast 250 (Authentication from scratch) which is intended for Rails 3 on Rails 4.
Obviously there is a problem of strong parameters which I think I have solved using the usual method.
I am currently getting this error:
undefined method `password' for #User:0xb640d880
Extracted source (around line #32):
respond_to do |format|
if #user.save
format.html { redirect_to #user, notice: 'User was successfully created.' }
format.json { render action: 'show', status: :created, location: #user }
else
I know the controller can access the password attribute, but for some reason the model can't even though I am validating the presence of :password in the model.
user.rb
class User < ActiveRecord::Base
before_save :encrypt_password
validates_confirmation_of :password
validates_presence_of :password, :on => :create
validates_presence_of :email
validates_uniqueness_of :email
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
end
users_controller.rb
class UsersController < ApplicationController
before_action :set_user, only: [:show, :edit, :update, :destroy]
# GET /users
# GET /users.json
def index
#users = User.all
end
# GET /users/1
# GET /users/1.json
def show
end
# GET /users/new
def new
#user = User.new
end
# GET /users/1/edit
def edit
end
# POST /users
# POST /users.json
def create
logger.warn user_params[:password]
#user = User.new(email: user_params[:email], password_hash: user_params[:password_hash], password_salt: user_params[:password_salt])
respond_to do |format|
if #user.save
format.html { redirect_to #user, notice: 'User was successfully created.' }
format.json { render action: 'show', status: :created, location: #user }
else
format.html { render action: 'new' }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
# PATCH/PUT /users/1
# PATCH/PUT /users/1.json
def update
respond_to do |format|
if #user.update(user_params)
format.html { redirect_to #user, notice: 'User was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: 'edit' }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
# DELETE /users/1
# DELETE /users/1.json
def destroy
#user.destroy
respond_to do |format|
format.html { redirect_to users_url }
format.json { head :no_content }
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_user
#user = User.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
params.require(:user).permit(:email, :password_hash, :password_salt, :password)
end
end
_form.html.erb (view)
<%= form_for(#user) do |f| %>
<% if #user.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#user.errors.count, "error") %> prohibited this user from being saved:</h2>
<ul>
<% #user.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :email %><br>
<%= f.text_field :email %>
</div>
<div class="field">
<%= f.label :password %><br>
<%= f.password_field :password %>
</div>
<div class="field">
<%= f.label :password %><br>
<%= f.password_field :password %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Thanks for your help!
I have created an sample project of user authentication so please check it.
Users_controller.rb
class UsersController < ApplicationController
def new
#user = User.new
end
def create
#user = User.new(user_params)
#raise params.inspect
if #user.save
redirect_to root_url, :notice => "Signed up!"
else
render "new"
end
end
private
def user_params
params.require(:user).permit(:email, :password_hash, :password_salt, :password)
end
end
new.html.erb
<h1>Sign Up</h1>
<%= form_for #user do |f| %>
<% if #user.errors.any? %>
<div class="error_messages">
<h2>Form is invalid</h2>
<ul>
<% for message in #user.errors.full_messages %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% 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 %>
<%= f.password_field :password_confirmation %>
</p>
<p class="button"><%= f.submit %></p>
<% end %>
user.rb
class User < ActiveRecord::Base
attr_accessor :password
before_save :encrypt_password
validates_confirmation_of :password
#validates_presence_of :password, :on => :create
validates_presence_of :email
validates_uniqueness_of :email
def encrypt_password
#raise password.inspect
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
end
Above code is working properly.
Your model is missing an attr_accessor for password. As you don't have a password column in your table but still need to receive the password attribute (so you can process it with a salt and then turn it into a hash), you need to have this accessor.
Add this in your user model:
attr_accessor :password
EDIT: Just like Amit Sharma pointed out in his demo.
I'm
I'm building a website on Ruby On Rails 3.0.7 and I want to save a store object and its languages. So, I have the following models:
class Store < ActiveRecord::Base
belongs_to :user
has_many :languages, :through => :store_languages
has_many :store_languages
accepts_nested_attributes_for :store_languages
#Validations
validates :title, :presence => true, :length => 5..100
validates :contact_email, :presence => true, :format => { :with => /^([^#\s]+)#((?:[-a-z0-9]+\.)+[a-z]{2,})$/i }
end
class Language < ActiveRecord::Base
has_many :stores, :through => :store_languages
has_many :store_languages
end
class StoreLanguage < ActiveRecord::Base
belongs_to :store
belongs_to :language
validates :store_id, :presence => true
validates :language_id, :presence => true
end
StoresController's relevant actions:
def new
#store = Store.new
#store.store_languages.build
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => #store }
end
end
# POST /stores
# POST /stores.xml
def create
#raise params.inspect
#store = current_user.stores.new(params[:store])
respond_to do |format|
if #store.save
format.html { redirect_to(#store, :notice => 'Store was successfully created.') }
format.xml { render :xml => #store, :status => :created, :location => #store }
else
#store.store_languages.build
format.html { render :action => "new" }
format.xml { render :xml => #store.errors, :status => :unprocessable_entity }
end
end
end
View: /stores/new.html.erb:
<%= form_for(#store) do |f| %>
<% if #store.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#store.errors.count, "error") %> prohibited this store from being saved:</h2>
<ul>
<% #store.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<p>
<label for="title">Title*</label><br />
<%= f.text_field :title %>
</p>
<p>
<label for="description">Description</label><br />
<%= f.text_field :description %>
</p>
<p>
<label for="contact_email">Contact E-mail*</label><br />
<%= f.text_field :contact_email %>
</p>
<p>
<label for="logo">Logo</label><br />
<%= f.file_field :logo %>
</p>
<% f.fields_for :store_languages do |lf| %>
<%= lf.collection_select :language_id, #languages, :id, :name, {}, {:multiple => true } %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
So, I've got the following records in the languages table:
id | name
3 English
4 EspaƱol
What happens is that when I create a new store selecting the two languages from the list, it will save the following at the store_languages table:
id | store_id | language_id
4 4 1
And the language_id = 1 doesn't exist.
If I debug the application at the create action, I get the following:
"store"=>{"title"=>"asdasdsdsadasdasdasd", "description"=>"", "contact_email"=>"asdasdsa#asdasdsad.com", "logo"=>"", "store_languages_attributes"=>{"0"=>{"language_id"=>["3", "4"]}}}
You can see that the ids are correct here: 3 and 4. So, I don't know why it saves 1.
Any ideas?
Try
<%= lf.collection_select :language_ids, #languages, :id, :name, {}, {:multiple => true } %>
(ie using ids instead of id in the attribute name)
Basically whats happening is I can create a new item that gets saved to my table in my db. but when I go to edit the item, the form opens up, I make the change and then when I go to submit, it takes me to the same url as the edit page and gives me Routing Error No route matches "/support/14/edit" although if you enter that in the address bar it opens the edit form just fine, but doesn't have any of my changes saved. So here is my code.
routes.rb
resources :support
support_controller.rb
def new
#support_item = Support.new
respond_to do |format|
format.html # new.html.erb
format.xml { render :xml => #support_item }
end
end
# GET /support/1/edit
def edit
#support_item = Support.find(params[:id])
end
# POST /support
# POST /support.xml
def create
#support_item = Support.new(params[:support_item])
respond_to do |format|
if #support_item.save
format.html { redirect_to("/support", :notice => 'Question was successfully created.') }
else
format.html { render :action => "new" }
end
end
end
# PUT /support/1
# PUT /support/1.xml
def update
#support_item = Support.find(params[:id])
respond_to do |format|
if #support_item.update_attributes(params[:support_item])
format.html { redirect_to("/", :notice => 'Question was successfully updated.') }
format.xml { head :ok }
else
format.html { render :action => "edit" }
format.xml { render :xml => #support_item.errors, :status => :unprocessable_entity }
end
end
end
support.rb
class Support < ActiveRecord::Base
belongs_to :role
scope :admin_available, order("role_id ASC") do
Support.all
end
def self.available(user)
questions = where(:role_id => 1)
questions += where(:role_id => user.roles)
questions
end
end
_form.html.erb
<% if #support_item.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#support_item.errors.count, "error") %> prohibited this question from being saved:</h2>
<ul>
<% #support_item.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label "Support item for:" %><br />
<%= f.collection_select :role_id, Role.find_by_max(5), :id, :name, {:default => 'everyone'} %>
</div>
<div class="field">
<%= f.label :question %><br />
<%= f.text_field :question, :class => 'genForm_question'%>
</div>
<div class="field">
<%= f.label :answer %><br />
<%= f.text_area :answer, :class => 'genForm_textarea' %>
</div>
<div class="field">
<%= f.label :url %><br />
<%= f.text_field :url, :class => 'genForm_question' %>
</div>
<div class="actions">
<%= f.submit %>
</div>
new.html.erb
<h1>New Support Item</h1>
<% form_for #support_item, :url => { :action => "create" }, :html => { :method => :post } do |f| %>
<%= render 'form', :f => f %>
<% end %>
edit.html.erb
<h1>Editing Support Item</h1>
<% form_for #support_item, :url => { :action => "edit" }, :html => { :method => :post } do |f| %>
<%= render 'form', :f => f %>
<% end %>
I believe thats all the relavent code.
<h1>Editing Support Item</h1>
<% form_for #support_item do |f| %>
<%= render 'form', :f => f %>
<% end %>
You are overriding the URL. It should be able to be auto-generated like that if you are doing everything with standard rest. If that doesn't work out, just know you don't want to submit to /support_items/1/edit, you want to submit to /support_items/1.