I am doing this for a school project and it is not working. :(
How do I get out the selected[petowner_id] from the view and make it usable in a ruby controller?
How do I make the #selected_pet = params([petowner_id]) in the controller that comes in from the view to function? Currently it renders an error message when I try to set it. :(
I am getting very tired of it not working.
The controller from Pets controller
class PetsController < ApplicationController
# GET /pets
# GET /pets.json
def monsters
#Finds the current user
if current_user
#user = current_user
#pets_kept = [] #why?
##petowner = Petowner.find(params[:petowner][:id])
#if(params[:commit])
#end
#monster = "Eeeep"
#mypets=[]
#all_my_pets = #user.petowners
#options value = 2
#params { selected_petowner[petowner_id]}
#selectpet = params{[selected][petowner_id]}
#petowner = Petowner.find_by_id(params[:id])
#pet = Pet.find_by_id(params[:pet_id])
#Find the petowners that the user currently has
##mypets = #user.petowners
#This is my way of doing things in a C++ fashion, I don't get all ruby things
#user.petowners.each do |pet|
##selected_pet = pet.find(params[:selected])
# if pet.hp != 0
# #pets_kept << pet #Dont recall seeing the << before in ruby but for C++ statement used for cout statements
#if pet.select
# #selected_pet = pet.select
#end
end
##selected_pet = Petowner.find(params[:petowner][:selected])
#end
#selected_pet = 1 ##user.petowners.find(params[:id])
#mypets = current_user.petowners.select{|pet| pet.hp !=0}
#raise "I am here"
##selected_pet = #mypets.find(params[:id][:selected])
##mypets = #pets_kept
end
The code from the view that doesn't go back to the controller variable and set it. :(
<select id="petowner_id" name="selected[petowner_id]">
<%= #all_my_pets.each do |pet| %>
<option value="<%= pet.id %>"><%= pet.pet_name %></option>
<% end %>
</select>
Previous step from pets/monsters view that doesn't work at all from previous collection. :(
<%= form_for :petowner, :url => petowner_fights_path(#selected_pet, #pet) do |f| %>
<p>Select a pet <%#= f.collection_select(:petowner, :petowner_id, #user.petowners, :petowner_id, :pet_name) %></p>
<%= render 'monsterinfo' %>
<div class="outer"></div>
<%= f.submit "Fight Selected Monster" %>
<% end %>
You probably want params[:petowner][:petowner_id]. Definitely don't construct the select with html in a view.
By the way, it's really helpful to see all of the params passed in to a controller action. I tend to raise params.to_yaml when I need to do that.
Related
I'm trying to get data out of this datamapper object and then putting it into a loop and getting the data out of the object that way, but it doesn't seem to be working, this is the code I have:
#user = User.get(session[:user])
#polls = []
polls = Poll.all(:user_id => #user)
polls.each do |poll|
pollname << poll.name
#polls << pollname
end
and in my erb file:
<% #polls.each do |poll| %>
<p><%= poll %></p>
<% end %>
I thinks what you want is:
#user = User.get(session[:user])
#polls = Poll.where(user_id: #user.id).all.collect { |p| p.name }
i need update a single record attribute but i canĀ“t. alumno_id is foreign key of model 'alumno'. the code show the records and if submit 'Aceptar' in one record, need a change the attribute estado to 1
in Model
class Postulacion < ActiveRecord::Base
attr_accessible :ramo, :estado, :alumno_id
belongs_to :alumno
end
in View
<h1>Lista de Postulaciones</h1>
<% #postulaciones.each do |p| %>
<% #id = p.id %>
<%= #id %>
<p>
<td><%= Alumno.find(p.alumno_id).full_name%></td>
<td><%='=> '+ p.ramo %></td>
<td><% if p.estado == 0 %>
<%= 'Pendiente =>' %>
<%= form_tag :action => 'aceptar' do %>
<%= submit_tag 'Aceptar' %></p>
<%end%>
<%else%>
<%='=> Aceptado' %>
<%end%>
</td>
</p>
<% end %>
in controller
class ListadoController < ApplicationController
def listar
#postulaciones = Postulacion.all
respond_to do |format|
format.html
format.json { render json: #postulaciones }
end
end
def aceptar
#postulacion = Postulacion.where(id: #id).first #Edit
#postulacion.estado = 1 #Edit
#postulacion.save #Edit
redirect_to "/"
end
end
Error "undefined method `update_attribute' for []:ActiveRecord::Relation"
Thanks
With this code:
#postulacion = Postulacion.where(alumno_id: #id )
You are declaring #postulacion as a collection, not as a single instance. You can fix this by calling .first:
#postulacion = Postulacion.where(alumno_id: #id ).first
Or by using find_by instead of where:
#postulacion = Postulacion.find_by(alumno_id: #id )
One other thing - this code isn't checking for the possibility that the Postulacion instance might not exist. You should add some logic to handle this...
Your #postulacion variable holds ActiveRecord::Relation instead of single ActiveRecord object. Try:
def acceptar
#postulacion = Postulacion.find_by_alumino_id(#id)
# ...
end
or, if you'd be using Rails 4:
#postulacion = Postulacion.find_by(alumino_id: #id)
View:-
<% #dating_advices.each do |da| %>
<% if da['is-displayed'][0]['content'] == 'true' %>
<div class="dating_advice">
<h4><%= da['title'][0] %></h4>
<p><b><%= da['author'][0] %></b></p>
<p><%= da['content'] %></p>
</div>
<hr>
<% end %>
<% end %>
Controller:-
def dating_advices
#current_menu = "MatchMasters"
logger.debug "*** Current site id: #{#current_site.id}"
##hide_quick_search = true
#passed_args = {
'event_action' => 'ws',
'site_id' => #current_site.site_id
}
result = call_dating_advices_ws(#passed_args)
if result && result['errorcode'][0] == 'success'
#dating_advices = result['payload'][0]['payload']
end
end
Now when I click on dating advices on my webpage it gives an error"Getting Template::Error (Undefined method 'each') for nil:NIL Class"
You probably didn't get any #dating_advices -- which would mean you're calling each on an instance var that doesn't exist.
The way your controller is written, #dating_advices is never defined if the result variable is not defined.
You could quickly patch it with a #dataing_advices = [] (or a hash -- anything with an .each method) and figure out why your controller is failing.
You could do something like
if result && result['errorcode'][0] == 'success'
... your dating advice code
else
raise result
(or #dating_advice = {})
end
basically you need to always defined #dating_advice OR you need to handle that value not being defined in your view.
i just don't get it, where did i do wrong.
please highlight them for me.
Im testing a graph using gruff.
in ReportController
def mygruff
#gr = Hash.new
#gr["jan"] = 3
#gr["feb"] = 6
logger.info({##gr.keys})
end
in my log, i did get 'janfeb'
in mygruff view
<%if #gr.blank?%>
<%=No gruff%>
<%else%>
<%=#gr.keys%>
<%end%>
I will get No gruff on mygruff page.
But i get it in my log.
Ive tried
object.empty?
true
object.blank?
true
object.nil?
false
how to get the hash in my view?
please show me the way.thank you.
def stat2
#cus_t = Hash.new
a = Gruff::Bar.new('500x350')
a.theme = {
:colors => ['#138F6A','#330000','#0aaafd','#FF0000','#00CD00','#ff6602', '#3bb003', '#1e90af', '#efba30', '#0aaaac'],
:marker_color => '#aaa',
:background_colors => ['#eaeaea', '#fff']
}
a.hide_title = true
#customer = Customer.find(:all)
#customer.each do |custs|
#g_cus = Casedf.count(:all, :conditions=> "customer_id=" + custs.id.to_s)
a.data(custs.companyname, #g_cus)
##cus_t[custs.companyname] = #g_cus
#cus_t.store(custs.companyname,#g_cus)
end
a.write("#{RAILS_ROOT}/public/images/customer.png")
$logger.info("hash keys #{#cus_t.keys}")
end # end def
Here is what I did on my view:
<table>
<% if #cus_t.nil?%>
<tr>
<td colspan="6">No cus added so far<%=#cus_t.keys%>l</td>
</tr>
<%else%>
<tr>
<td><%=#cus_t.keys%></td>
</tr>
<%end%>
</table>
So when I browse to stat2's page, I get nothing, but in my logs, the keys are printed out. I'm stumped, please help.
Hi Do you have in your action
def mygruff
#gr = Hash.new
#gr["jan"] = 3
#gr["feb"] = 6
logger.info({##gr.keys})
end
it was not clear for me from comment
In Ruby, hashes don't have a blank? method. That method is added by Rails and there may be a bug with it. Please try this in your view:
<% if #gr.empty? %>
No gruff
<% end %>
<%= #gr.inspect %> <!-- print regardless to see if there is data there -->
I have form that create two objects and save them to database.
I want to do next things:
save data in database (booth objects)
validate fields (I have validation in model)
and if validation fail, I want to populate fields with entered data
edit action for this form
Problems:
If I use #report I get:
Called id for nil, which would
mistakenly be 4 error
(can't find object). I have in controller, in encreate action #report = ReportMain.new and in action that render that view.
When I use :report_main (model name) it works, it save data to database, but I can't get fields populated when validation fails.
Questions:
What to do with this two models to make this to work (validation, populating fields, edit)?
Can you give me some advice if approach is wrong?
My view looks like this:
<%= form_for(#report, :url => {:action => 'encreate'}) do |f| %>
<%= render "shared/error_messages", :target => #report %>
<%= f.text_field(:amount) %>
<% fields_for #reporte do |r| %>
<%= r.check_box(:q_pripadnost) %>Pripadnost Q listi
<%= 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']])) %>
<%= r.text_field(:ispitivanjebroj) %>
<%= r.text_field(:datumispitivanja) %>
<% end %>
<input id="datenow" name="datenow" size="30" type="text" value="<%= #date %>">
<div class="form-buttons">
<%= submit_tag("Unesi izvestaj") %>
</div>
<% end %>
encreate actin in ReportController:
def encreate
#report = ReportMain.new
#reporte = ReportE.new
#reportparam = params[:report_main]
#report.waste_id = params[:waste][:code]
#report.warehouse_id = Warehouse.find_by_user_id(current_user.id).id
#report.user_id = current_user.id
#report.company_id = current_user.company_id
#report.amount = #reportparam[:amount]
#report.isimport = false
#report.isfinished = false
#report.reportnumber = ReportMain.where(:company_id => current_user.company_id, :isimport => false).count.to_i+1
if #report.save
#reporte.report_main_id = #report.id
else
redirect_to(:action => 'exportnew')
return
end
#reporte.vrstaotpada = params[:vrstaotpada]
#reporte.nacinpakovanja = params[:nacinpakovanja]
#reporte.ispitivanjebroj = #reportparam[:ispitivanjebroj]
#reporte.datumispitivanja = #reportparam[:datumispitivanja]
#reporte.q_pripadnost = #reportparam[:q_pripadnost]
#reporte.datumpredaje = #date
if #reporte.save
redirect_to(:action => 'show', :id => #reporte.id)
else
redirect_to(:action => 'exportnew')
end
end
I think your problem in this case is that you use redirect_to instead of render. When you use redirect_to then you lose all the variables from your current action. I would probably do something like this in your encreate action:
if #reporte.save
render :show
else
render :exportnew
end
When you use render then it will use the variables from the current action but the view from the action you send to the render method. So when form_for is called with the #report variable, it is already populated with the values that was sent to encreate. Just make sure that you use the same variable names in the different actions but it looks like you do that already.