undefined method `belogns_to' - ruby-on-rails

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.

Related

Select_tag with elasticsearch

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 %>

ActionView::Template::Error (undefined method `strip!' for nil:NilClass)

It seems I'm running into this error when I insert more than 100,000 records. I know it can support way more than that. The error is below and the code for the related classes.
2015-07-01 08:14:24.512:INFO:/:Started GET "/search?type=digital_object" for 129.118.15.44 at 2015-07-01 08:14:24 -0500|
2015-07-01 08:14:24.512:INFO:/:Processing by SearchController#search as HTML|
2015-07-01 08:14:24.512:INFO:/: Parameters: {"type"=>"digital_object"}|
Jul 01, 2015 8:14:24 AM org.apache.solr.core.SolrCore execute
INFO: [collection1] webapp= path=/select params={facet=true&sort=title_sort+asc&facet.limit=100&qf=four_part_id^3+title^2+finding_aid_filing_title^2+fullrecord&wt=json&rows=10&defType=edismax&pf=four_part_id^4&start=0&q=*:*&facet.field=repository&facet.field=primary_type&facet.field=subjects&facet.field=source&facet.field=linked_agent_roles&fq=types:("digital_object")&fq=-exclude_by_default:true&fq=publish:true} hits=203799 status=0 QTime=15
2015-07-01 08:14:24.590:INFO:/: Rendered G:/archivesspace/plugins/vva/public/views/search/_components_switch.html.erb (15.0ms)|
2015-07-01 08:14:24.590:INFO:/: Rendered search/_filter.html.erb (0.0ms)|
2015-07-01 08:14:24.606:INFO:/: Rendered search/_pagination_summary.html.erb (16.0ms)|
2015-07-01 08:14:24.637:INFO:/: Rendered search/_inline_results.html.erb (47.0ms)|
2015-07-01 08:14:24.637:INFO:/: Rendered search/results.html.erb within layouts/application (62.0ms)|
2015-07-01 08:14:24.653:INFO:/:Completed 500 Internal Server Error in 141.0ms|
2015-07-01 08:14:24.653:INFO:/:|ActionView::Template::Error (undefined method `strip!' for nil:NilClass):|
17: <% elsif result["primary_type"] === "repository" %>|
18: <%= link_to result['title'], :controller => :search, :action => :repository, :repo_id => id %>|
19: <% else %>|
20: <%= link_to title_or_finding_aid_filing_title( result ) , :controller => :records, :action => result["primary_type"], :id => id, :repo_id => repo_id %>|
21: <% end %>|
22: </h3>|
23: <div class="result-summary">| app/helpers/application_helper.rb:22:in `title_or_finding_aid_filing_title'|
app/views/search/_inline_results.html.erb:20:in `_app_views_search__inline_results_html_erb___996910774_15116'|
app/views/search/_inline_results.html.erb:5:in `_app_views_search__inline_results_html_erb___996910774_15116'|
app/helpers/application_helper.rb:134:in `render_aspace_partial'|
app/views/search/results.html.erb:13:in `_app_views_search_results_html_erb__332589766_15048'|
app/controllers/search_controller.rb:21:in `search'|
app/controllers/search_controller.rb:20:in `search'|||
_inline_results.html.erb
<div class="search-results">
<% if search_data.results? %>
<%= render_aspace_partial :partial => "search/pagination_summary", :locals => {:search_data => search_data} %>
<ul class="results-list">
<% search_data['results'].each do |result| %>
<%
id = JSONModel(result["primary_type"]).id_for(result['uri'])
repo_id = JSONModel(:repository).id_for(JSONModel.repository_for(result['uri']),{}, true)
%>
<li class="result">
<h3>
<%= icon_for result["primary_type"] %>
<% if result["primary_type"] === "subject" %>
<%= link_to result["title"], {"filter_term" => search_data.facet_query_string("subjects", result["title"])} %>
<% elsif ["agent_person", "agent_software", "agent_family", "agent_corporate_entity"].include?(result["primary_type"]) %>
<%= link_to result['title'], :controller => :records, :action => :agent, :id => id, :agent_type => result["primary_type"] %>
<% elsif result["primary_type"] === "repository" %>
<%= link_to result['title'], :controller => :search, :action => :repository, :repo_id => id %>
<% else %>
<%= link_to title_or_finding_aid_filing_title( result ) , :controller => :records, :action => result["primary_type"], :id => id, :repo_id => repo_id %>
<% end %>
</h3>
<div class="result-summary">
<%= render_aspace_partial :partial => "search/result_summary_#{result["primary_type"]}", :locals => {:obj => result} %>
</div>
</li>
<% end %>
</ul>
<%= render_aspace_partial :partial => "search/pagination", :locals => {:search_data => search_data} %>
<% else %>
<p class="alert alert-info">
<%= I18n.t("search_results.no_results") %></em>.
</p>
<% end %>
</div>
search_controller.rb
require 'advanced_query_builder'
class SearchController < ApplicationController
DETAIL_TYPES = ['accession', 'resource', 'archival_object', 'digital_object',
'digital_object_component', 'classification',
'agent_person', 'agent_family', 'agent_software', 'agent_corporate_entity']
VIEWABLE_TYPES = ['agent', 'repository', 'subject'] + DETAIL_TYPES
FACETS = ["repository", "primary_type", "subjects", "source", "linked_agent_roles"]
def search
set_search_criteria
#search_data = Search.all(#criteria, #repositories)
#term_map = params[:term_map] ? ASUtils.json_parse(params[:term_map]) : {}
respond_to do |format|
format.html { render "search/results" }
format.js { render_aspace_partial :partial => "search/inline_results", :content_type => "text/html", :locals => {:search_data => #search_data} }
end
end
def advanced_search
set_advanced_search_criteria
#search_data = Search.all(#criteria, #repositories)
render "search/results"
end
def repository
set_search_criteria
if params[:repo_id].blank?
#search_data = Search.all(#criteria.merge({"facet[]" => [], "type[]" => ["repository"]}), {})
return render "search/results"
end
#repository = #repositories.select{|repo| JSONModel(:repository).id_for(repo.uri).to_s === params[:repo_id]}.first
#breadcrumbs = [
[#repository['repo_code'], url_for(:controller => :search, :action => :repository, :id => #repository.id), "repository"]
]
#search_data = Search.repo(#repository.id, #criteria, #repositories)
render "search/results"
end
private
def set_search_criteria
#criteria = params.select{|k,v|
["page", "q", "type", "sort",
"filter_term", "root_record", "format"].include?(k) and not v.blank?
}
#criteria["page"] ||= 1
#criteria["sort"] = "title_sort asc" unless #criteria["sort"] or #criteria["q"] or params["advanced"].present?
if #criteria["filter_term"]
#criteria["filter_term[]"] = Array(#criteria["filter_term"]).reject{|v| v.blank?}
#criteria.delete("filter_term")
end
if params[:type].blank?
#criteria['type[]'] = DETAIL_TYPES
else
#criteria['type[]'] = Array(params[:type]).keep_if {|t| VIEWABLE_TYPES.include?(t)}
#criteria.delete("type")
end
#criteria['exclude[]'] = params[:exclude] if not params[:exclude].blank?
#criteria['facet[]'] = FACETS
end
def set_advanced_search_criteria
set_search_criteria
terms = (0..2).collect{|i|
term = search_term(i)
if term and term["op"] === "NOT"
term["op"] = "AND"
term["negated"] = true
end
term
}.compact
if not terms.empty?
#criteria["aq"] = AdvancedQueryBuilder.new(terms, :public).build_query.to_json
#criteria['facet[]'] = FACETS
end
end
def search_term(i)
if not params["v#{i}"].blank?
{ "field" => params["f#{i}"], "value" => params["v#{i}"], "op" => params["op#{i}"], "type" => "text" }
end
end
end
application_helper.rb
module ApplicationHelper
def include_theme_css
css = ""
css += stylesheet_link_tag("themes/#{ArchivesSpacePublic::Application.config.public_theme}/bootstrap", :media => "all")
css += stylesheet_link_tag("themes/#{ArchivesSpacePublic::Application.config.public_theme}/application", :media => "all")
css.html_safe
end
def set_title(title)
#title = title
end
def title_or_finding_aid_filing_title(resource)
if resource["finding_aid_filing_title"] && !resource["finding_aid_filing_title"].nil? && resource["finding_aid_filing_title"].length > 0
title = resource["finding_aid_filing_title"]
elsif resource["title"] && !resource["title"].nil?
title = resource["title"]
else
title = resource["display_string"]
end
MixedContentParser::parse(title, url_for(:root))
end
def icon_for(type)
"<span class='icon-#{type}' title='#{I18n.t("#{type}._singular")}'></span>".html_safe
end
def label_and_value(label, value)
return if value.blank?
label = content_tag(:dt, label)
value = content_tag(:dd, value)
label + value
end
def i18n_enum(jsonmodel_type, property, value)
return if value.blank?
property_defn = JSONModel(jsonmodel_type).schema["properties"][property]
return if property_defn.nil?
if property_defn.has_key? "dynamic_enum"
enum_key = property_defn["dynamic_enum"]
#return "enumerations.#{enum_key}.#{value}"
I18n.t("enumerations.#{enum_key}.#{value}", :default => value)
else
I18n.t("#{jsonmodel_type}.#{property}_#{value}", :default => value)
end
end
def params_for_search(opts = {})
search_params = {
:controller => :search,
:action => :search
}
search_params["filter_term"] = Array(opts["filter_term"] || params["filter_term"]).clone
search_params["filter_term"].concat(Array(opts["add_filter_term"])) if opts["add_filter_term"]
search_params["filter_term"] = search_params["filter_term"].reject{|f| Array(opts["remove_filter_term"]).include?(f)} if opts["remove_filter_term"]
search_params["sort"] = opts["sort"] || params["sort"]
search_params["q"] = opts["q"] || params["q"]
search_params["format"] = params["format"]
search_params["root_record"] = params["root_record"]
search_params["agent_type"] = params["agent_type"]
search_params["page"] = opts["page"] || params["page"] || 1
if opts["type"] && opts["type"].kind_of?(Array)
search_params["type"] = opts["type"]
else
search_params["type"] = opts["type"] || params["type"]
end
search_params["term_map"] = params["term_map"]
# retain any advanced search params
advanced = (opts["advanced"] || params["advanced"])
search_params["advanced"] = advanced.blank? || advanced === 'false' ? false : true
search_params[:action] = :advanced_search if search_params["advanced"]
(0..2).each do |i|
search_params["v#{i}"] = params["v#{i}"]
search_params["f#{i}"] = params["f#{i}"]
search_params["op#{i}"] = params["op#{i}"]
end
search_params.reject{|k,v| k.blank? or v.blank?}
end
def set_title_for_search
title = I18n.t("actions.search")
if #search_data
if params[:type] && !#search_data.types.blank?
title = "#{I18n.t("search_results.searching")} #{#search_data.types.join(", ")}"
end
facets_to_display = []
if #search_data.query?
facets_to_display << #search_data.facet_label_for_query
end
if #search_data.filtered_terms?
facets_to_display << #search_data[:criteria]["filter_term[]"].collect{|filter_term| #search_data.facet_label_for_filter(filter_term)}
end
if facets_to_display.length > 0
title += " | #{facets_to_display.join(", ")}"
end
end
set_title(title)
end
def truncate(string, length = 50, trailing = '…')
return string if string.length < length
"#{string[0..50]}#{trailing}".html_safe
end
# See: ApplicationController#render_aspace_partial
def render_aspace_partial(args)
defaults = {:formats => [:html], :handlers => [:erb]}
return render(defaults.merge(args))
end
def proxy_localhost?
AppConfig[:frontend_proxy_url] =~ /localhost/
end
end
I got it figured out. Looks like some of the data imported had blank titles "". By updating them it was able to work.
The error is in your _inline_results.html.erb...
<% elsif result["primary_type"] === "repository" %>
<%= link_to result['title'], :controller => :search, :action => :repository, :repo_id => id %>
the error is that the result['title'] is nil. so, add this line of code....
<% elsif result["primary_type"] === "repository" %>
<% if !result['title'].blank? %>
<%= link_to result['title'], :controller => :search, :action => :repository, :repo_id => id %>
<% end %>

Rails 4 Cannot access hash in nested form (undefined method `[]' for nil:NilClass)

I've build quite complex form which creates one prescription with many realtions. I am using this syntax in view:
- provide(:title, 'Create prescription')
%h1 Add medicines to prescription
.row
.span6.offset3
= form_for #prescription do |f|
= render 'shared/error_prescription_messages'
%p
= f.hidden_field :patient_id, :value => params[:patient_id]
= f.hidden_field :user_id, :value => current_user.id
= f.fields_for :relations do |builder|
= render 'child_form', :f => builder
%p= f.submit "Submit"
chlid_form is quite simple :
- it=f.options[:child_index].to_i
- n= it.to_s
%h2
= "Medicine ##{it+1}"
= f.hidden_field :medicine_id, :id => "my_medicine_id#{it}"
- if params[:prescription].nil? || params[:prescription][:relations_attributes][n.to_sym][:medicine_name].nil?
= f.autocomplete_field :medicine_name, autocomplete_medicine_name_relations_path, :id_element => "#my_medicine_id#{it}"
- else
= f.autocomplete_field :medicine_name, autocomplete_medicine_name_relations_path, :id_element => "#my_medicine_id#{it}", :value => params[:prescription][:relations_attributes][n.to_sym][:medicine_name]
= f.label :amount, "Amount of medicine boxes"
= f.number_field :amount, :value => 1
= f.label :daily
= f.number_field :daily, :value => 1
= f.label :period_in_days, "Duration of treatment (in days)"
= f.number_field :period_in_days, :value => 1
So as you can see I'm using f.options[:child_index] to get index of child (0,1,2...) cause I generate multiple items with this particular form. I then put it to variable it and sucessfully use it in :id_element => "#my_medicine_id#{it}" which works PERFECTLY fine (creates my_medicine_id0, my_medicine_id1 ....) Although it doesn't work in this line:
:value => params[:prescription][:relations_attributes][n.to_sym][:medicine_name]
where n is just n=it.to_s.
I though somethings wrong in controller but if I change this line to whatever
:value => params[:prescription][:relations_attributes]**[:'0']**[:medicine_name] or any other integer from 0 to 4 everything works great, but I NEED dynamic change in this one. So I got proof that it DOES work because it generates integer fine here "#my_medicine_id#{it}" but won't work in hash! And when I print the whole hash from params I get this:
{"patient_id"=>"7", "user_id"=>"1", "relations_attributes"=>{"0"=>{"medicine_id"=>"13490", "medicine_name"=>"Locacid 500 mcg/g (0,05%) (1 tuba 30 g)", "amount"=>"0", "daily"=>"1", "period_in_days"=>"1"}, "1"=>{"medicine_id"=>"", "medicine_name"=>"", "amount"=>"1", "daily"=>"1", "period_in_days"=>"1"}, "2"=>{"medicine_id"=>"", "medicine_name"=>"", "amount"=>"1", "daily"=>"1", "period_in_days"=>"1"}, "3"=>{"medicine_id"=>"", "medicine_name"=>"", "amount"=>"1", "daily"=>"1", "period_in_days"=>"1"}, "4"=>{"medicine_id"=>"", "medicine_name"=>"", "amount"=>"1", "daily"=>"1", "period_in_days"=>"1"}}}
so to get the values I need it's pretty obvious that
params[:prescription][:relations_attributes][SOME_KIND_OF_INETEGER][:medicine_name] should work, but doesn't.
Controller code:
class PrescriptionsController < ApplicationController
before_action :signed_in_user
before_action :doctor_user, only: [:new, :create]
before_action :pharmacist_user, only: [:update]
def new
#prescription =Prescription.new
5.times { #prescription.relations.build }
end
def create
#prescription = Prescription.new(new_prescription_params)
if #prescription.save
flash[:success] = "Prescription created."
redirect_to #prescription
else
5.times { #prescription.relations.build }
render 'new', :prescription => params[:prescription]
end
end
def show
#prescription = Prescription.find(params[:id])
#medicines = #prescription.medicines.paginate(page: params[:page], :per_page => 10)
end
def update
#prescription = Prescription.find(params[:id])
#patient = Patient.find(params[:patient_id])
if !prescription_expired?(#prescription)
#prescription.realized = 1
if #prescription.save
flash[:success] = "Prescription realized."
redirect_to #patient
else
redirect_to root_url
end
else
flash[:notice] = "Can't realize, prescription expired."
redirect_to #patient
end
end
private
def new_prescription_params
params.require(:prescription).
permit(:patient_id, :user_id, relations_attributes: [:medicine_id, :medicine_name, :amount, :daily, :period_in_days])
end
def doctor_user
redirect_to(root_url) unless current_user.function == "doctor"
end
def pharmacist_user
redirect_to(root_url) unless current_user.function == "pharmacist"
end
def prescription_expired?(presc)
presc.created_at < 1.month.ago
end
def signed_in_user
unless signed_in?
store_location
flash[:notice] = "Please log in."
redirect_to login_url
end
end
end
I run out of ideas so I ask you guys if anyone can help. Thanks.
There is no point in using params in your view since you already assigned those to your models. Also when you rendering your new action, those params doesn't exist as nothing has been send to the server yet. Just get rid of all the values from inputs.
Your partial should look like:
- it=f.options[:child_index].to_i
- n= it.to_s
%h2
= "Medicine ##{it+1}"
= f.hidden_field :medicine_id, :id => "my_medicine_id#{it}"
= f.autocomplete_field :medicine_name, autocomplete_medicine_name_relations_path
= f.label :amount, "Amount of medicine boxes"
= f.number_field :amount
= f.label :daily
= f.number_field :daily
= f.label :period_in_days, "Duration of treatment (in days)"
= f.number_field :period_in_days
If you want your fields to have default value, set default value inside your database.

Parameter in AJAX request

I have a view which contain multiple links:
<% a.each do |q| %>
<%= link_to "stock it",
{ :action => "stock",
:qid => q.question_id,
:qur => q.question_answers_url,
:qti => q.title } ,
:remote => true %>
<div id="<%= "stock" + q.question_id.to_s %>"></div>
<% end %>
Each link generate AJAX-request. Here is a controller:
def stock
if(!Later.where(:question_id => params[:qid]).exists?)
later = Later.new(:question_id => params[:qid], :name => params[:qti], :url => params[:qur])
later.save
end
respond_to do |format|
format.js { render :layout=>false }
end
end
Now return to the view. Each link has a 'div' with unique id='stock'. When user press the link I need to add text to specific div with corresponding id.
I have a stock.js.erb file:
$("#stock<number>").html("some text");
How can I pass div-id to stock.js.erb and how can I use it ?
Common use is to add object.id to your DOM id. That what you exactly did:
<div id="<%= "stock_#{q.question_id}" %>"></div>
Then in your controller you shoud define your question_id or your exact question:
def stock
if(!Later.where(:question_id => params[:qid]).exists?)
later = Later.new(:question_id => params[:qid], :name => params[:qti], :url => params[:qur])
later.save
end
#question_id = params[:qid]
end
Now it will be shared with your stock.js.erb file:
$("#stock_<%= #question_id %>").html("some text");

Rails form params changing in controller

I have a form:
<%= form_for(:report_main, :url => {:action => 'exporttoxiccreate'}) do |f| %>
<%= collection_select(:waste, :code, Waste.find_all_by_istoxic(false), :id, :code, :include_blank => '') %>
<%= f.check_box(:q_pripadnost) %>
<%= f.text_field(:amount) %>
<% end %>
and this code in controller:
def exporttoxiccreate
#report = ReportMain.new
#reportexport = ReportExport.new
#reportparam = params[:report_main]
#report.waste_id = #reportparam.waste.code
#report.amount = #reportparam.amount
if #report.save
#reportexport.report_main_id = #report.id
else
redirect_to(:action => 'exporttoxicnew')
end
#reportexport.q_pripadnost = #reportparam.q_pripadnost
if #reportexport.save
redirect_to(:action => 'show', :id => #reportexport.id)
else
redirect_to(:action => 'exporttoxicnew')
end
end
I want to save in two tables, in two objects data from this form, and I need to separate params to manipulate with. I tried with this:
#reportexport.q_pripadnost = #reportparam.q_pripadnost
I want to set q_pripadnost field in #reportexport with some value from param.
Where I make mistake?
When you get params from a form in Rails, it comes in the form of a hash. For example:
params[:report_main][:waste]
params[:report_main][:amount]
So when you call #reportparam = params[:report_main], you are setting #reportparam to a hash, but then you are trying to use it later like an object. For example, instead of #reportparam.q_pripadnost, use #reportparam[:q_pripadnost].
You can take a closer look at your variable by temporarily changing your action to show a text version of the variable, for example:
def exporttoxiccreate
#reportparam = params[:report_main]
render :text => #reportparam.to_yaml
end

Resources