My f.select is not working
this is my form -
- #anonymous.each do |a|
=form_for #confession , html: {multipart: true} do |f|
=f.label :Confess
=f.text_area :confession , require: true
=f.label :post_as
=f.select(:postid,options_for_select([[#confession.amitian.fullname,#confession.amitian.fullname],[a.fullname,a.fullname]]))
=f.file_field :confessionimage
=f.submit 'Confess'
and this is my controller class ..
def index
#amitian = Amitian.where(institute: current_amitian.institute) if amitian_signed_in?
#confessions = Confession.where(amitian_id: #amitian.ids).order('created_at DESC') if amitian_signed_in?
#anonymous = Amitian.where(email: 'anonymous#anonymous.com')
#anonymous.each do |a|
#debug = a
if params[:postid] == 'Anonymous'
#confession = a.confessions.build
else
#confession = current_amitian.confessions.build
end
end
end
my if statement is never true ... why ?
A clear f.select statement from above is this =
f.select(:postid,options_for_select('yourname','Anonymous')
so whenever user select anonymous if statement should return true
You need to check params[:postid] in create action, not in index.
Related
First, sorry for my bad English. I'm still learning.
I have 3 tables in my DB:
Problem
has_many :registers
has_many :solutions, through : :registers
Solution
has_many :problems
has_many :problems, through : :registers
Register
belongs_to: problem
belongs_to :solution
The system is working well. I am able to insert new data in all of the 3 tables.
In the views for the table/model Register, to select problems and solutions, I make use of collection_select, like this:
= form_for #register do |f|
.field
= f.label :problem_id
= collection_select( :register, :problem_id, #problems, :id, :name, {}, { :multiple => false })
.field
= f.label :solution_id
= collection_select( :register, :solution_id, #courses, :id, :name, {}, { :multiple => false })
.field
= f.label :entry_at
= f.datetime_select :entry_at
.actions = f.submit
The problem only appears when I try to add this validation to Register:
validates_uniqueness_of :student_id , scope: :course_id
Then I get:
> undefined method `map' for nil:NilClass
> = collection_select( :register, :problem_id, #problems, :id, :name, {}, { :multiple => false })
And I dont know why.
So, I tried to do the validation by the controller:
def create
#register = Register.new(register_params)
problem_id = #register.problem_id
solution_id = #register.solution_id
if Register.exists?(['problem_id LIKE ? AND solution_id LIKE ?', problem_id, solution_id ])
render 'new'
else
#register.save
respond_with(#register)
end
end
But the error remains.
I believe that the cause is the collection_select, but I don't know how to solve it.
Saying one more time, I am able to persist date in all the 3 DB tables. But when I try to avoid duplication, the error appears.
This is how I solve this problem:
def create
#register = register.new(register_params)
#if #register.save
# respond_with(#register)
#else
# #register = register.all
# render :new
#end
problem_id = #register.problem_id
solution_id = #register.solution_id
if register.exists?(['problem_id LIKE ? AND solution_id LIKE ?', problem_id, solution_id ])
#register = register.new
#solutions = Solution.all
#problems = Problem.all
flash[:error] = "Problem alread in the register for this solution"
render 'new'
else
#register.save
respond_with(#register)
end
end
I try to pass 2 options for search. First [:q] for input text by visitor and another one from model camping "nomdep" (like departement in english). When i try to search by input it's works, but since i try to add select_tag i have an error
ERROR
undefined method `map' for nil:NilClass
I m lost, do u have any ideas ?
Sorry for my english, i m french.
Home_controler.rb
def index
if params[:q].nil?
"Entrez un mot clef"
else
#campings = Camping.__elasticsearch__.search params[:q,:nomdep]
#camping = Camping.all
end
end
def result
if params[:q].nil?
#campings = []
else
#campings = Camping.__elasticsearch__.search(params[:q]).page(params[:page]).per(14).results
end
end
View
<div class="search">
<%= form_tag(result_path, method: :get) %>
<%= text_field_tag :q, params[:q], class:"search-query form-control" %>
<%= select_tag(:nomdep, options_for_select(#camping)) %>
<%= submit_tag "Partez", class:"btn btn-danger", name: nil %>
</div>
EDIT
Now i dont have any error but the search dont work if [:q] empty. So if i only select_tag => no result.
How fix this ?
My full home_controller.rb
class HomeController < ApplicationController
def index
#camping = Camping.all
if params[:q].nil?
"Entrez un mot clef"
else
#campings = Camping.__elasticsearch__.search params[:q, :nomdep]
end
end
def result
if params[:q].nil?
#campings = []
else
#campings = Camping.__elasticsearch__.search(params[:q]).page(params[:page]).per(14).results
end
end
end
my view
<div class="search">
<%= form_tag(result_path, method: :get) %>
<%= select_tag :nomdep, options_from_collection_for_select(#camping, :id, :nomdep), prompt: "Département" %>
<%= text_field_tag :q, params[:q], class:"search-query form-control" %>
<%= submit_tag "Partez", class:"btn btn-danger", name: nil %>
</div>
#camping = Camping.all
This variable will be nil unless :q was passed in params to index action. options_for_select(#camping) will attempt to call #map on this variable and raise error when it is not initialized.
You should make sure it is initialized. For example, try rewriting your action:
def index
#camping = Camping.all
if params[:q].nil?
"Entrez un mot clef"
else
#campings = Camping.__elasticsearch__.search params[:q]
end
end
I want to say a big big big THANKS to #Baradzed ! We talked yesterday and he find a solution thats work perfectly !
home_controller.rb
class HomeController < ApplicationController
def index
#camping = Departement.all
if params[:q].blank? || params[:nomdep].blank?
#campings = Camping.__elasticsearch__.search params[:nomdep]
else
#campings = Camping.__elasticsearch__.search params[:q]
end
end
def result
querystring = params.slice(:nomdep, :other_param, :any_params_except_q_because_we_will_process_q_separately)
.select{|k,v| v.present?}
.map {|key, value| "#{key}:\"#{value.gsub(/([#{Regexp.escape('\\+-&|!(){}[]^~*?:/')}])/, '\\\\\1') }\""}
.join(" AND ")
freetext = params[:q]
freetext.gsub!(/([#{Regexp.escape('\\+-&|!(){}[]^~*?:/')}])/, '\\\\\1')
querystring = ["*#{freetext}*",querystring].select{|v| v.present?}.join(" AND ") if params[:q].present?
if querystring.blank?
flash[:notice] = "Aucune mots clefs"
redirect_to action: :index and return
else
#campings = Camping.__elasticsearch__.search(
query: { query_string: {
query: querystring
}}).page(params[:page]).per(14).results
end
#hash = Gmaps4rails.build_markers(#campings) do |camping, marker|
marker.lat camping.latitude
marker.lng camping.longitude
marker.infowindow render_to_string(:partial => "/campings/infowindow", :locals => { :camping => camping})
marker.picture ({
"url" => "http://avantjetaisriche.com/map-pin.png",
"width" => 29,
"height" => 32})
end
end
end
view
<div class="search">
<%= form_tag(result_path, method: :get) %>
<%= select_tag :nomdep, options_from_collection_for_select(#camping, :nomdep, :nomdep), prompt: "Département" %>
<%= text_field_tag :q, params[:q], class:"search-query form-control" %>
<%= submit_tag "Partez", class:"btn btn-danger", name: nil %>
I've got a simple search form, in rails 4 app, that needs two params passed to be able to show relevant data.
I'm getting an 'Mysql2::Error: Unknown column 'data inputted' but the columns do exist. If I instead of '#search = Page.where(params[:one] && params[:two])' use '#search = Page.all' the data shows, but all of it shows.
Form
<%= form_tag(page_show_path, id: "search-form") do %>
<%= text_field_tag :one, params[:one], placeholder: "One" %>
<%= text_field_tag :two, params[:two], placeholder: "Two" %>
<%= submit_tag "Search", :name => nil %>
<% end %>
Model
def self.one(query)
where("one = ?", "%#{query}%")
end
def self.two(query)
where("two = ?", "%#{query}%")
end
Controller
def show
if (params[:one] && params[:two]).present?
#search = Page.where(params[:one] && params[:two])
else
redirect_to page_path, notice: "Not a valid combination"
end
end
You can Create and Use Scope.
scope :find_one_two, ->(query_one, query_two) { where("one = ? AND two = ? ", query_one, query_two) }
#search = Page.find_one_two(params[:one], params[:two])
OR
You can use.
#search = Page.where("one = ? AND two = ?", params[:one], params[:two])
def show
if (params[:one] && params[:two]).present?
#search = Page.where("one like ? AND two like ? ", "%#{params[:one]}%", "%#{params[:two]}%")
else
redirect_to page_path, notice: "Not a valid combination"
end
end
This may solve your problem.
I do not have much idea on jQuery/Ajax. Could someone help me to submit the forms dynamically
here is the requirement:
- I have set of tests
- Each test has a result
- Each test result stored as separate record
I am thinking of following approach:
- display each test result as a separate form and submit each one of them using AJAX
I hope there would be a better approach, please help me
here are my code:
//results controller
class ResultsController < ApplicationController
def index
#results = Result.all
#tests = Tests.all
end
def new
#result = Result.new
end
//view
#tests.each do |test|
= form_for(#result) do |r|
= r.label :test_id, test.name
= r.hidden_field :test_id, :value => test_id
= r.select :status, options_for_select(%w[UNTESTED PASS FAIL PENDING BLOCKED INVALID])
= r.submit "Submit"
The index action from controller will call index page
In index page
= #tests.each do |test|
#test.#{test.id}= render partial: "test", :locals => {test: test}
create one _test.html page In _test page do all this,
= form_for(test) do |test|
= r.label :test_id, test.name
= r.hidden_field :test_id, :value => test_id
= r.select :status, options_for_select(%w[UNTESTED PASS FAIL PENDING BLOCKED INVALID])
= r.submit "Submit"
create one index.js.html file
:plain
$("#test_#{#test.id}").html("#{escape_javascript(render(:partial => "test", :locals => { :test => #test}))}");
I have some code in view:
<%= form_for(:report_main, :url => {:action => 'exporttoxiccreate'}) do |f| %>
<%= select_tag('vrstaotpada',options_for_select([['Komercijalni otpad', 'Komercijalni otpad'], ['Industrijski otpad', 'Industrijski otpad']])) %>
<%= collection_select(:waste, :code, Waste.find_all_by_istoxic(false), :id, :code, :include_blank => '') %>
<%= f.check_box(:q_pripadnost) %>
<%= f.text_field(:amount) %>
<%= select_tag('nacinpakovanja',options_for_select([['Drveno bure', 'Drveno bure'], ['Kanister', 'Kanister'], ['Sanduk', 'Sanduk'], ['Kese', 'Kese'], ['Posude pod pritiskom', 'Posude pod pritiskom'], ['Kompozitno pakovanje', 'Kompozitno pakovanje'], ['Rasuto', 'Rasuto'], ['Ostalo', 'Ostalo']])) %>
<%= f.text_field(:ispitivanjebroj) %>
<%= f.text_field(:datumispitivanja) %>
<% end %>
and this in controller "report_main":
def exporttoxiccreate
#report = ReportMain.new
#reportexport = ReportExport.new
#reportparam = params[:report_main]
#report.waste_id = #reportparam.waste.code
#report.warehouse_id = 1
#report.user_id = 1
#report.company_id = 1
#report.amount = #reportparam.amount
#report.isimport = false
#report.isfinished = false
if #report.save
#reportexport.report_main_id = #report.id
else
redirect_to(:action => 'exporttoxicnew')
end
#reportexport.vrstaotpada = #reportparam.vrstaotpada
#reportexport.nacinpakovanja = #reportparam.nacinpakovanja
#reportexport.ispitivanjebroj = #reportparam.ispitivanjebroj
#reportexport.datumispitivanja = #reportparam.datumispitivanja
#reportexport.q_pripadnost = #reportparam.q_pripadnost
if #reportexport.save
redirect_to(:action => 'show', :id => #reportexport.id)
else
redirect_to(:action => 'exporttoxicnew')
end
end
And when I submit the form I got strange error:
undefined method `belogns_to' for
Why I need belongs_to method? What goes there?
Sounds like you're trying to create an active record assocation of belongs_to but mispelled it to belogns_to. So go check your model.