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
Related
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
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>
This is my first time with Cocoon, and maybe this is a really dumb question, but I already spend many time looking how to do this with ERB template and avoid using simple_form or other helper.
Take a look of my models:
models/loot.rb
class Lot < ActiveRecord::Base
has_many :colindanciums, dependent: :destroy
has_many :cardinal_points, through: :colindanciums
accepts_nested_attributes_for :colindanciums, allow_destroy: true
end
models/colindancium.rb
class Colindancium < ActiveRecord::Base
belongs_to :cardinal_poing
belongs_to :lot
end
models/cardinal_point.rb
class CardinalPoint < ActiveRecord::Base
has_many :colindanciums
has_many :lots, through: :colindanciums
end
The form:
views/lots/_form.html.erb
<%= form_for(#lot, remote: true) do |f| %>
<%= render 'shared/error_messages', object: #lot %>
...
...
...
<fieldset id="colindancium-orientation">
<ol>
<%= f.fields_for :colindanciums do |colindancium| %>
<%= render 'colindancium_fields', f: colindancium %>
<% end %>
</ol>
<%= link_to_add_association 'Nueva Colindancia', f, :colindanciums, 'data-association-insertion-node' => "#colindancium-orientation ol", 'data-association-insertion-method' => "append" %>
</fieldset>
...
...
...
<% end %>
The partial:
views/lots/_colindancium_fields.html.erb
<li class="control-group nested-fields">
<div class="controls">
<%= f.label :description, "Descripcion:" %>
<%= f.text_field :description %>
<%= f.label :linear_meters, "Metros Lineales:" %>
<%= f.text_field :linear_meters %>
<%= f.label :cardinal_point_id, "Orientacion:" %>
<%= f.select :cardinal_point_id,
options_from_collection_for_select(CardinalPoint.all, :id, :name), { }, { :class => "form-control", :prompt => "Seleccione un Punto Cardinal" } %>
<%= link_to_remove_association "Eliminar", f %>
</div>
</li>
Everything works great when I insert new fields, it saves it in DB, it Update it in DB, my problem is in the options_from_collection_for_select when I open the form in Edit Action, the fourth parameter of this helper is the selected value... I can't find the way to make selected the value that is stored in my db, it always show the 1 index... I can't access the #... object from the _form, the other fields (:description, :linear_meters) are working quite good my problem is in the f.select, I don't know how to do it.
EDIT My controller:
# GET /lots/new
def new
#lot = Lot.new
#lot.colindanciums.build
authorize #lot
end
# PATCH/PUT /lots/1
# PATCH/PUT /lots/1.json
def update
authorize #lot
respond_to do |format|
if #lot.update(lot_params)
format.html { redirect_to #lot, notice: 'Lot was successfully updated.' }
format.json { render :show, status: :ok, location: #lot }
format.js
else
format.html { render :edit }
format.json { render json: #lot.errors, status: :unprocessable_entity }
format.js { render json: #lot.errors, status: :unprocessable_entity }
end
end
end
I change my logic in the select, i made it works in this way:
<div class="form-group">
<%= f.label :cardinal_point_id, "Orientacion:", :class => "control-label" %>
<%= f.select :cardinal_point_id , CardinalPoint.all.collect {|p| [ p.name, p.id ] }, { :include_blank => 'Seleccione un Punto Cardinal'}, :class => "form-control" %>
</div>
I post my answer in case anybody have the same issue.
You forgot to put the parenthesis correctly
<%= f.select (:cardinal_point_id,
options_from_collection_for_select(CardinalPoint.all, :id, :name), { }, { :class => "form-control", :prompt => "Seleccione un Punto Cardinal" }) %>
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 -%>
I need a form that allows users to accept 4 set of inputs to invite four users into an entity. The following is the code.
# GET /company_members/new
def new
#company_member = CompanyMember.new
#company_member.company_members.build
end
# POST /company_members
# POST /company_members.json
def create
#company_member = CompanyMember.new(company_member_params)
#company_member.user_id = 1
#company_member.company_id = 1
respond_to do |format|
if #company_member.save
format.html { redirect_to #company_member, notice: 'Company member was successfully created.' }
format.json { render action: 'show', status: :created, location: #company_member }
else
format.html { render action: 'new' }
format.json { render json: #company_member.errors, status: :unprocessable_entity }
end
end
end
Form:
<%= form_for(#company_member) do |f| %>
<!--<% if #company_member.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#company_member.errors.count, "error") %> prohibited this company_member from being saved:</h2>
<ul>
<% #company_member.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>-->
<%= f.fields_for #company_member do |yes| %>
email: <%= yes.text_field :email %> role: <%= yes.collection_select :company_member_role_id, CompanyMemberRole.all, :id, :name, :prompt => "Please select" %>
<% end %><br>
<%= f.fields_for #company_member do |yes| %>
email: <%= yes.text_field :email %> role: <%= yes.collection_select :company_member_role_id, CompanyMemberRole.all, :id, :name, :prompt => "Please select" %>
<% end %><br>
<%= f.fields_for #company_member do |yes| %>
email: <%= yes.text_field :email %> role: <%= yes.collection_select :company_member_role_id, CompanyMemberRole.all, :id, :name, :prompt => "Please select" %>
<% end %>
<div class="field">
<%= f.label :email %>
<%= f.text_field :email %>
<%= show_errors(#company_member, :email) %>
</div>
<!--<div class="field">
<%= f.label :company_id %><br>
<%= f.collection_select :company_id, Company.all, :id, :name %>
</div>-->
<div class="field">
<%= f.label :company_member_role_id %>
<%= f.collection_select :company_member_role_id, CompanyMemberRole.all, :id, :name, :prompt => "Please select" %>
<%= show_errors(#company_member, :company_member_role_id) %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
It just saves one Row in the Database while it has to save 4 rows. Also is there a way to remove the un filled rows if any?