Error is not showing using different controller - ruby-on-rails

In my task show page, I have form for creating a response and the responses are displayed here as well. (Task has many responses)
views\tasks\show.html.erb
<%= simple_form_for([#task, Response.new]) do |f| %>
<%= f.input :is_comment, as: :hidden %>
<%= f.input :negotiate_pay, label: false %>
<%= f.input :comment_text, as: :text, input_html: {rows: 3}, label: false %>
<div class="row">
<div class="col-md-4 col-md-offset-8">
<%= f.button :submit %>
</div>
</div>
</div>
<% end %>
<br>
<div id="comments">
<%= render #responses %>
</div>
controllers\tasks_controller
def show
#task = Task.find(params[:id])
#responses = #task.responses.all
end
controllers\responses_controller
def create
#task = Task.find(params[:task_id])
#response = #task.responses.create(response_params)
#response.user_id = current_user.id
#response.is_comment = params[:is_comment]
#response.save
respond_to do |format|
format.html { redirect_to #task }
format.js
end
end
It is working alright but it doesn't show the errors in the form after validation and submit. How can I show the error message in response form which is in the show page of task. I am using a simple_form btw.
Help please
EDIT:
Models:
models\response.rb
belongs_to :user
belongs_to :task
has_many :subcomments
default_scope -> { order('created_at DESC') }
#VALIDATIONS
validates :comment_text, presence: true
validates :negotiate_pay, presence: true

You need to add the code that will display the errors to your form :
<%= simple_form_for([#task, Response.new]) do |f| %>
<% if #response.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#response.errors.count, "error") %> prohibited this response from being saved:</h2>
<ul>
<% #response.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
and you also need to tweak your create action in the responsesController:
def create
#task = Task.find(params[:task_id])
#response = #task.responses.build(response_params)
#response.user_id = current_user.id
#response.is_comment = params[:is_comment]
respond_to do |format|
if #response.save
format.html { redirect_to #task, notice: "response was createad" }
format.js
else
format.html { render :show }
end
end
also make sure you are displaying the errors inside your application.html.erb :
<% if flash[:error] -%>
<p class='alert alert-danger'><%=h flash[:error] %></p>
<% end -%>
<% if flash[:notice] -%>
<p class='alert alert-success'><%=h flash[:notice] %></p>
<% end -%>

Related

NoMethodError in Products#add , undefined method `errors' for nil:NilClass

i have no idea why this error come out, can anyone help me? thanks
It shown when i comment out the product controller( def add) there.
And also if possible is that can help me check the add.html.erb there is that my option_for_select to get all the outlets correct?
Errors show in website
Errors show in console
ActionView::Template::Error (undefined method `errors' for nil:NilClass
#virtual_path = "shared/_error_messages";object = local_assign
s[:object]; object = object;; if object.errors.any?
^^^^^^^):
1: <% if object.errors.any? %>
2: <div id="error_explanation">
3: <div class="alert alert-danger">
4: The form contains <%= pluralize(object.errors.count, "error")
%>.
app/views/shared/_error_messages.html.erb:1
app/views/products/add.html.erb:5
app/views/products/add.html.erb:4
Add.html.erb
<h1>Add to outlet</h1>
<div class="row">
<div class="col-md-6 col-md-offset-3">
<%= form_with(model: #product, local: true) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<%= f.label :name %>
<%= f.text_field :name, class: 'form-control' %>
<%= f.label :quantity %>
<%= f.number_field :quantity, class: 'form-control' %>
<%= f.label :price %>
<%= f.number_field :price, class: 'form-control' %>
<%= f.label :outlet %>
<%= f.select :outlet, options_for_select(#outlets), :include_blank => true %>
<%= f.hidden_field :category_id, value: 1 %>
<%= f.submit "Save changes", class: "btn btn-primary" %>
<% end %>
_error_messages.html.erb
<% if object.errors.any? %>
<div id="error_explanation">
<div class="alert alert-danger">
The form contains <%= pluralize(object.errors.count, "error") %>.
</div>
<ul>
<% object.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
Product Controller
class ProductsController < ApplicationController
def category
#category = Category.find(params[:id])
end
def index
#products = Product.all
end
def show
#product = Product.find(params[:id])
end
def new
#product = Product.new
#product.category_id = params[:category_id]
end
def create
#product = Product.new(product_params)
#category_id = Category.find(params[:product] [:category_id])
if #product.save
flash[:success] = "Succesful create!"
redirect_to #product
else
render 'new'
end
end
def outlet
#outlet = Outlet.find(params[:id])
end
def add
##product = Product.find(params[:id])
##outlet = Outlet.find(params[:outlet_id])
end
def update
#product = Product.find(params[:id])
#outlet = Outlet.find(params[:outlet][:name])
if #product.update(product_params)
flash[:success] = "Product updated"
redirect_to #product
else
render 'add'
end
end
private
def product_params
params.require(:product).permit(:name, :quantity, :price,
:category_id)
end
end

Why Ajax call is responding after a page refresh in rails 4?

Suppose I have defined my create action like this:
def create
#appointment = Appointment.find(params[:appointment_id])
#note = #appointment.notes.new(notes_params)
#note.user_id = current_user.id
respond_to do |format|
if #note.save
format.html { redirect_to appointment_path(#appointment), notice: "Saved successfully" }
format.js
else
format.html { render 'new', notice: "Try again" }
format.js
end
end
end
My create.js.erb is like this:
$("#note_field").html("<%= j render partial: 'note', locals: {note: #note} %>");
Here is my form:
<%= form_for([#appointment, #appointment.notes.build({user: current_user})], remote: true) do |f| %>
<div>
<% if #note && #note.errors.any? %>
<% #note.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
<% end %>
</div>
<div class="field">
<%= f.label :Description %><br>
<%= f.text_area :description, required: true %>
</div>
<div>
<%= f.submit class: "note-button" %>
</div>
<% end %>
Here, note is partial form. How to make it work without a page refresh?

Rails join collection not recognizing parameters

I'm trying to create a record in a join table named Interventions. Basically in my application a user can do many interventions on an incident, and an incident can have interventions by many users. I pass the needed strong parameters, but the application gives the following errors when I try to save: "Incident must exist" and "User must exist". I spent hours on this, and can't figure out what is the problem. Can you please help me? I post the relevant code here:
user.rb (model)
has_many :interventions
has_many :incidents, through: :interventions
incident.rb (model)
has_many :interventions
has_many :users, through: :interventions
intervention.rb (model)
belongs_to :incident_priority
belongs_to :intervention_status
interventions_controller.rb
def new
#incident = Incident.find(params[:incident])
#user = User.find(current_user.id)
#intervention = Intervention.new(:user_id => #user, :incident_id => #incident)
#project = #incident.channel.project
#mirth = Mirth.find_by server_id: #incident.mirth_server_id
end
def create
#incident = Incident.find(params[:incident_id])
#user = User.find(params[:user_id])
#intervention = Intervention.create(intervention_params)
#project = #incident.channel.project
#mirth = Mirth.find_by server_id: #incident.mirth_server_id
respond_to do |format|
if #intervention.save
format.html { redirect_to new_intervention_path(#incident), notice: 'Intervention was successfully created.' }
format.json { render :show, status: :created, location: #intervention }
else
format.html { render :new, incident: :incident_id }
format.json { render json: #intervention.errors, status: :unprocessable_entity }
end
end
end
< .... >
def intervention_params
params.require(:intervention).permit(:user_id, :incident_id, :incident_priority_id, :begin_date, :end_date, :description,
:intervention_status_id, :forwarded_to)
end
In my view (interventions_form.html.erb):
<%= form_for(#intervention) do |f| %>
<% if #intervention.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#intervention.errors.count, "error") %> prohibited this intervention from being saved:</h2>
<ul>
<% #intervention.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="form-group form-inline">
<%= hidden_field_tag :user_id, #user.id %>
<%= hidden_field_tag :incident_id, #incident.id %>
<strong>Interveniente:</strong>
<%= #user.first_name %> <%= #user.last_name %>
</div>
<div class="form-group form-inline">
<%= f.label 'Prioridade' %>
<%= f.collection_select :incident_priority_id, IncidentPriority.all, :id, :description, {}, {class: "form-control"} %>
</div>
<div class="form-group form-inline">
<%= f.label 'Data início intervenção' %>
<%= f.datetime_select :begin_date %>
</div>
<div class="form-group form-inline">
<%= f.label 'Data fim intervenção' %>
<%= f.datetime_select :end_date, :include_blank => true %>
</div>
<div class="form-group form-inline">
<%= f.label 'Observações' %>
<%= f.text_area :description %>
</div>
<div class="form-group form-inline">
<%= f.label 'Estado' %>
<%= f.collection_select :intervention_status_id, InterventionStatus.all, :id, :description, {}, {class: "form-control"} %>
</div>
<div class="form-group form-inline">
<%= f.label 'Encaminhado para:' %>
<%= f.text_area :forwarded_to %>
</div>
<div class="actions" align="right">
<%= link_to 'Voltar', incidents_path(:mirth => #mirth, :project => #project), class: "btn btn-info" %>
<%= f.submit "Gravar", class: "btn btn-info" %>
</div>
I run debug and the values in the hidden_field_tags are correctly filled. Also in the controller the #user and #incident are correctly populated, but #intervention has nil in the foreign keys :user_id and :incident_id.
Thanks in advance!
You need to associate the user and the incident with the intervention.
in your model...
class Intervention
belongs_to :user
belongs_to :incident
in your create method...
def create
#incident = Incident.find(params[:incident_id])
#user = User.find(params[:user_id])
#intervention = Intervention.create(intervention_params)
#intervention.incident = #incident
#intervention.user = #user
...
You need to change this:
def create
#incident = Incident.find(params[:incident_id])
#user = User.find(params[:user_id])
# ...
end
For this:
def create
#incident = Incident.find(params[:incident_id])
#user = User.find(params[:user_id])
intervention_params.merge(user_id: #user.id, incident_id: #incident.id)
# ...
end
And your model:
class Intervention
belongs_to :user
belongs_to :incident

How to call one model form field into another controller index?

Todos Controller
class TodosController < ApplicationController
# GET /todos
# GET /todos.json
def index
#todos = Todo.all
#projects = Project.new
respond_to do |format|
format.html # index.html.erb
format.json { render :json => #todos }
end
end
# GET /todos/1
# GET /todos/1.json
def show
#todo = Todo.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render :json => #todo }
end
end
# GET /todos/new
# GET /todos/new.json
def new
#todo = Todo.new
respond_to do |format|
format.html # new.html.erb
format.json { render :json => #todo }
end
end
# GET /todos/1/edit
def edit
#todo = Todo.find(params[:id])
end
# POST /todos
# POST /todos.json
def create
#todo = Todo.new(params[:todo])
respond_to do |format|
if #todo.save
format.html { redirect_to(#todo, :notice => 'Todo was successfully created.') }
format.json { render :json => #todo, :status => :created, :location => #todo }
else
format.html { render :action => "new" }
format.json { render :json => #todo.errors, :status => :unprocessable_entity }
end
end
end
# PUT /todos/1
# PUT /todos/1.json
def update
#todo = Todo.find(params[:id])
respond_to do |format|
if #todo.update_attributes(params[:todo])
format.html { redirect_to(#todo, :notice => 'Todo was successfully updated.') }
format.json { render :json => {} }
else
format.html { render :action => "edit" }
format.json { render :json => #todo.errors, :status => :unprocessable_entity }
end
end
end
# DELETE /todos/1
# DELETE /todos/1.json
def destroy
#todo = Todo.find(params[:id])
#todo.destroy
respond_to do |format|
format.html { redirect_to(todos_url) }
format.json { render :json => {} }
end
end
def newproject
#projects = Project.all
end
end
Todos_form.html.erb
<%= form_for(#todo) do |f| %>
<% if #todo.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#todo.errors.count, "error") %> prohibited this todo from being saved:</h2>
<ul>
<% #todo.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :content %><br />
<%= f.text_field :content %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
projects_form.html.erb
<%= form_for(#project) do |f| %>
<% if #project.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#project.errors.count, "error") %> prohibited this project from being saved:</h2>
<ul>
<% #project.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_area :name %>
</div>
<div class="field">
<%= f.label :project_id %><br />
<%= f.number_field :project_id %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
project.rb
class Project < ActiveRecord::Base
attr_accessible :name, :project_id
has_many :todos
def as_json(options = {})
super(options.merge(:only => [ :id, :name, :project_id]))
end
end
todo.rb
class Todo < ActiveRecord::Base
attr_accessible :content, :order, :done
belongs_to :project
def as_json(options = {})
super(options.merge(:only => [ :id, :content, :order, :done ]))
end
end
Hi I have two models Todos and Projects, in Todos index i want to show projects field values. How it is possible help me how to proceed it.
And i need Associations also.
Note: The field values must be comes from project controller and save it Database.
First project model should not have project_id column. project_id should be present in the todo model.
Then change your routes.
resources :projects do
resources :todos
end
Now add the code to project controller.
class ProjectsController < ApplicationController
def index
#projects = Project.all
end
def show
#project = Project.find(params[:id])
#todos = #project.todos.all
end
def new
#project = Project.mew
end
def create
#project = Project.new(params[:project])
if #project.save
.....
else
....
end
end
end
Individual project contains its own todos. So that in project show page you can display all the todos associated with the project.
Now the todo controller should be look like:
class TodosController < ApplicationController
def new
#project = Project.find(params[:project_id])
#todo = #project.todos.new
end
def create
#project = Project.find(params[:project_id])
#todo = #project.todos.build(params[:todo])
if #todo.save
.....
else
....
end
end
def show
#project = Project.find(params[:project_id])
#todo = #project.todos.find(params[:id])
end
end
Finally in app/views/projects/new.html.erb file add the following code:
<%= form_for #project do |f| %>
<% if #project.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#project.errors.count, "error") %> prohibited this project from being saved:</h2>
<ul>
<% #project.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_area :name %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
And in app/views/todos/new.html.erb add the code:
<%= form_for #todo, url: project_todos_path(#project), method: :post do |f| %>
<% if #todo.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#todo.errors.count, "error") %> prohibited this todo from being saved:</h2>
<ul>
<% #todo.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :content %><br />
<%= f.text_field :content %>
</div>
<div class="actions">
<%= f.submit %>
</div>

Pass multiple selected parameters to a submission link

I have a setup attempting to automate submission to a backend. There are 3 different dropdown boxes with user-selectable parameters. I set up my website like this (all 'scaffolds'):
class Xsearch < ActiveRecord::Base
has_many :xentry
has_many :spectrafile
has_many :parameter
end
Each entry/file/parameter has the belongs_to :xsearch in their model.
The index.html.erb of the xsearch has the following:
<h1>Spectra Submitter</h1>
<h2>Select a database to search</h2>
<%= collection_select("xpost", :id, Xentry.all(), :title, :name ) %>
<h2>Select a parameter file to use</h2>
<%= collection_select(:ppost, :id, Parameter.all(), :name, :name ) %>
<h2>Select a Spectra file (or folder) to search</h2>
<%= collection_select(:spost, :id, Spectrafile.all(), :name, :name ) %>
<%= link_to "Search", :controller => "xsearches", :action => "search" %>
I've tried using submit_tag as well. I have no idea how to trigger a method in my controller (if it should be in the controller? Since it's from the browser I assumed to put it here) that has the selected values from each collection_select.
So in short: How can I take the selected values for each collection_select and pass them to a function? Where should that function be placed (in the controller or in the .html.erb file)?
Thanks, this has been driving me crazy.
I ended up solving the issue by moving to a form_new method. Here's my code for anyone else who is searching. The purpose of this script was to allow other users to submit a search to a cluster through an authorized user.
<%= form_for(#xsearch) do |f| %>
<% if #xsearch.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#xsearch.errors.count, "error") %> prohibited this xsearch from being saved:</h2>
<ul>
<% #xsearch.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<h2>Pick A Database To Search</h2>
<%= collection_select(:db, :id, #all_entries, :id, :name) %>
<h2>Pick A Parameter File To Use</h2>
<%= collection_select(:para, :id, #all_parameters, :id, :name) %>
<h2>Pick a File or Folder To Search</h2>
<%= collection_select(:sfile, :id, #all_spectrafiles, :id, :name) %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
And the relevant bit in the controller's create: method
def create
#database = Xentry.find(params[:db][:id])
#paramfile = Parameter.find(params[:para][:id])
#spectrafile = Spectrafile.find(params[:sfile][:id])
#recurse = params[:recurse]
#email = params[:emailtag]
if #email.empty?
#email = "None"
end
if (#recurse == 'Yes')
#recurse = 1
else
#recurse = 0
end
#recurse = 0#disabled until kill methods are implemented
#hostname = hostname
#username = username
Net::SSH.start(#hostname, #username) do |session|
session.exec('source .bashrc')
session.exec('sh rscript.sh %s %s %s %s %d' % [#database['name'], #spectrafile['name'], #paramfile['name'], #email, #recurse])
#xsearch = Xsearch.new(:database => #database['name'], :parameters => #paramfile['name'], :spectra => #spectrafile['name'])
respond_to do |format|
if #xsearch.save
format.html { redirect_to #xsearch, notice: 'Search was successfully created.' }
format.json { render json: #xsearch, status: :created, location: #xsearch }
else
format.html { render action: "new" }
format.json { render json: #xsearch.errors, status: :unprocessable_entity }
end
end
end
end

Resources