link_to text - using ruby code for html text - ruby-on-rails

I want the Link text on my view to display as Hospital, Country. Country is a guidelines attribute so I need to be able to access guidelines.country from 'hospital' and display it
e.g. Get Well Hospital, Sickland
I'm not sure how to code this correctly. At the moment in my view file I have
<% #list.each do |hospital| %>
<tr class="tablerow">
<td><%= link_to (hospital, country), :action => :topichospital, :hospital => hospital, :country=>country %></td>
</tr>
It worked when I just had, but I'm not sure how to add the country too
<% #list.each do |hospital| %>
<tr class="tablerow">
<td><%= link_to hospital, :action => :topichospital, :hospital => hospital %></td>
</tr>
my listhospital action in guidelines_controller.rb is
def listhospital
#list = Guideline.order(:hospital).uniq.pluck(:hospital)
respond_to do |format|
format.html # index.html.erb
format.json { render json: #guidelines }
end
end

change your link_to to
<%= link_to "#{hospital}, #{country}", { :action => :topichospital, :hospital => hospital, :country=>country } %>
This will convert the first parameter passed to string. I'm not sure how rails interprets (hospital, country) in a link_to when passed as the first parameter but this will make sure to call the to_s methods for each.
UPDATE: IIRC, you can use pluck to combine attributes
# postgre
#list = Guideline.order(:hospital).uniq.pluck("hospital || ', ' || country")
# mysql
#list = Guideline.order(:hospital).uniq.pluck("CONCAT(hospital, ', ', country)")
then you can just use link_to hospital in the view.
UPDATE: This is becoming a bit of a hack. I suggest you change the controller to
#list = Guideline.select('hospital, country').order(:hospital).uniq
Then in your view
<% #list.each do |guideline| %>
<tr class="tablerow">
<td><%= link_to "#{guideline.hospital}, #{guideline.country}", { :action => :topichospital, :hospital => guideline.hospital, :country => guideline.country }%></td>
</tr>
<% end %>

I think you're looking for:
<%= link_to "#{hospital}, #{country}", :action => :topichospital, :hospital => hospital, :country=>country %>
You could also pass a block to link_to:
<%= link_to :action => :topichospital, :hospital => hospital, :country=>country do %>
<%= hospital %>, <%= country %>
<% end %>
http://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-link_to

Related

How to use Rails 5.2 form_with to trigger a specific action?

My application needs to duplicate a Skill (from skills index) as many times the user needs it in his cart. So I decided to trigger the add-to-cart method of the skills_controller when the related form, including the number of duplicates and the Skill's id, is submitted. For this purpose, I added counter to the strong parameters of skills_controller.
Unfortunately, I am missing something to correctly setup the form: when submitted, it triggers the create method. Here is the code:
routes.rb extract
resources :skills, :path => "variables" do
resources :values_lists
member do
post :add_to_cart
get :create_values_list
get :upload_values_list
get :remove_values_list
end
collection do
get :index_all
end
end
skills_controller.rb method
def add_to_cart
#template_skill = Skill.find(params[:id])
iterations = params[:skill][:counter].to_i
until iterations == 0
#skill = #template_skill.deep_clone include: [:translations, :values_lists]
#skill.business_object_id = session[:cart_id]
#skill.template_skill_id = #template_skill.id
#skill.code = "#{#template_skill.code}-#{Time.now.strftime("%Y%m%d:%H%M%S")}-#{iterations}"
#skill.is_template = false
#skill.save
iterations -= 1
end
#business_object = BusinessObject.find(session[:cart_id])
redirect_to #business_object, notice: t('SkillAdded2BO') # 'Skill successfully added to business object'
end
index.html.erb table content
<tbody>
<% #skills.each do |skill| %>
<tr data-href="<%= url_for skill %>">
<% if not session[:cart_id].nil? %>
<td>
<%= form_with model: #skill, :action => "add_to_cart", :method => :post, remote: false do |f| %>
<%= f.text_field :counter, value: "1", class: "mat-input-element", autofocus: true %>
<button type="submit" class="mat-icon-button mat-button-base mat-primary add-button" title="<%= t('AddToUsed') %>">
<span class="fa fa-plus"></span>
</button>
<% end %>
</td>
<% end %>
<td class="no-wrap"><%= skill.code %></td>
<td><%= link_to skill.translated_name, skill %></td>
<td><%= link_to translation_for(skill.parent.name_translations), skill.parent %></td>
<td><%= skill.responsible.name %></td>
<td><%= skill.updated_by %></td>
<td class="text-right"><%= format_date(skill.updated_at) %></td>
</tr>
<% end %>
</tbody>
Thanks a lot for your help!
According to this form helpers guide, the syntax you used doesn't exist
form_with model: #model, action: :custom_action
So in this case, you have to specify the url parameter for form_with to make it works.
<%= form_with model: #skill, url: :add_to_cart_skill_path(#skill), method: :post, remote: false do |f| %>

How to set two different actions for single form in Ruby on rails

In my application , I have one form in view which shows registered examinees with check boxes. Admin has the authority to confirm and reject the examinees. In my controller i have two methods , one for approve and another for reject. But i am not able to define correct method (action) in form. Because I want approve method to approve the examinees and reject for rejection.I am new to ruby on rails . Please Help me how to resolve this problem. I am pasting related source below.
welcome_controller.rb
class WelcomeController < ApplicationController
filter_access_to :all
#layout "home"
layout :choose_layout
def confirm_registration
#all_approved_users = params[:check_examinee]
#all_approved_users.each do|approved|
#user = User.find_by_id(approved.to_i)
#user.update_attributes(:is_approved => 1)
if (#user.is_approved == 0 and #user.confirmed == false) or (#user.is_approved == 1 and #user.confirmed == false) or (#user.is_approved == 2 and #user.confirmed == false)
UserMailer.user_registration_email_confirmation(#user,$pwd).deliver
end
end
flash[:success] = t('flash_success.email_verification')
respond_to do |format|
format.html { redirect_to :back }
format.js
end
end
def reject_registration
#rejected_users = params[:check_examinee]
#rejected_users.each do|rejected|
#user = User.find_by_id(rejected.to_i)
unless (#user.is_approved == 2 and #user.confirmed == false)
#user.update_attributes(:confirmed => false,:is_approved => 2)
UserMailer.examinee_registration_rejection(#user).deliver
end
end
flash[:success] = t('flash_success.email_rejection')
respond_to do |format|
format.html { redirect_to :back }
format.js
end
end
end
activation.html.erb
<%unless #registered_examinees.empty?%>
<% form_tag :action => ' ', :method => :post, :class => 'confirm_reject',:id => "class_form" do %>
<div class="questionTabele">
<table border="0" cellspacing="0">
<tr class="updateHeader">
<th><%= t('general.name')%></th>
<th><%= t('general.email')%></th>
<th><%= t('general.status')%></th>
<th> <%unless #unapproved_examinees.blank?%>
<%= check_box "checkall", "checkall", :title => "Select all unconfirmed users", :onclick => "checkUncheckAll(this,check_examinee_);" %>
<%else%>
<%= check_box "checkall", "checkall", :disabled => true, :title => "Select all unconfirmed users" %>
<%end%> </th>
</tr>
<% #registered_examinees.each do|examinee| %>
<tr class="updateAltrRow <%= cycle("odd", "even") %>">
<td><%= examinee.name%></td>
<td><%= examinee.email%></td>
<td> <%if examinee.confirmed == true%>
<%= t('user.confirmed')%>
<%elsif examinee.confirmed == false and examinee.is_approved == 0%>
<%= t('user.approve')%>
<%elsif examinee.confirmed == false and examinee.is_approved == 2%>
<%= t('user.reject')%>
<%else%>
<%= t('user.pending')%>
<%end%> </td>
<td> <%unless examinee.confirmed == true%>
<%= check_box_tag "check_examinee[]", examinee.id, false, {:class=>"validate[minCheckbox[1]] checkbox"} %>
<%end%> </td>
</tr>
<%end%>
</table>
</div>
<%= submit_tag t('general.approve'), :id=>"confirm", :class=>'btnBg' %> <%= submit_tag t('general.reject'), :id=>"reject", :class=>'btnBg' %>
<%= will_paginate #registered_examinees,
:prev_label => t('general.previous'),
:next_label => t('general.next'),
:page_links =>true,
:renderer => PaginationListLinkRenderer
%>
<% end %>
<%else%>
<div class="formContainer">
<%= t('not_found.no_examinee_found')%>
</div>
<% end %>
Need to change anything in routes.rb. Please tell me still I am learning ruby on rails.Thanks in advance.
I think that you might be solving this issue at the wrong level. Sometimes the best solution is to avoid the difficult problem all together.
What if you where to only have one controller method (name suggestion: expedite_users) and one parameter sent from the form would determine if it was accepting or rejecting. Seems to me that much of the code in both your methods where very similar any way.
Here is a question about having multiple buttons in a single form: How do I create multiple submit buttons for the same form in Rails?

update multiple records in one form using checkboxes / wrong number of arguments rails 4

I've been bumbling my way through tutorials/forums in an attempt to figure out how update multiple methods using checkboxes.
I need to be able to list my "events" and check or uncheck them if the date is available. I'd like to do this on one form. I know this is possible, but I'm finally coming here after failing to get it working.
With the code I've posted I'm getting "Wrong Number of Arguments, 2 for 1" error.
I've tried these info sources:
http://railscasts.com/episodes/52-update-through-checkboxes
http://discuss.codeschool.io/t/surviving-apis-with-rails-posting-multiple-records/4776/4
http://railscasts.com/episodes/165-edit-multiple-revised
Here's where I'm at
routes.rb
resources :events do
collection do
put :verified
post :make_events
end
end
events_controller.rb
def verified
if Event.update_all(["available", true], :id => params[:event_ids])
redirect_to step2_path(:pid => #project.id, :u => current_user.id)
else
end
end
show.html.erb
<%= form_tag verified_events_path(:pid => #project.id ), method: :put do %>
<table class="table-event-dates">
<thead>
<tr>
<th> </th>
<th> </th>
</tr>
</thead>
<tbody>
<tr><% #these_events.each do |event| %>
<td><%= check_box_tag "event_id[]", event.id, :value => event.available %></td>
<td><label> <%= event.date.strftime("%A, %b. %d %G") %></label></td>
</tr>
</tbody>
<% end %>
</table>
</div><br><!-- panel-body -->
<div class="panel-footer2">
<div class="row">
<%= submit_tag 'Verify Dates', :class => 'btn btn-green btn-lg btn-block' %>
<% end %>
Probably it should work in old-fashioned style:
Event.update_all("available = 1", ["id in (?)", params[:event_ids]])
perhaps available = true or 'true', i'm not sure. Or:
Event.update_all(["available", true], ["id in (?)", params[:event_ids]])
However, maybe you should clear params. Check that they are in correct form (1, 2, 4..).
Also you could try this:
Event.where(id: params[:event_ids]).update_all(available: true)
This question has been stale for a while but for what it's worth, the other error in the code provided that NothingToSeeHere mentions in the comment is:
In the view you have singular event_id
<%= check_box_tag "event_id[]", event.id, :value => event.available %>
In the controller you have plural event_ids
Event.update_all(["available", true], :id => params[:event_ids])
Both the params need to match and be plural. Zishe's last example for how to handle the update on the controller side is the convention for Rails 4.
<%= check_box_tag "event_ids[]", event.id, :value => event.available %>
Event.where( :id => params[:event_ids] ).update_all( :available => true )

Ruby on Rails Render Partial

I have a model called Listing that I use to represent a listing for a sublet. I created a model called Filter that I use to filter the sublets based on a form that the user fills out. Upon filling out the form, I want the user to be redirected to a template that has all of the listings that were returned from the filter.
Here is my Filter model.
class Filter < ActiveRecord::Base
attr_accessible :air_conditioning, :available_rooms, :bathrooms, :furnished, :negotiable, :new, :parking, :maximum_price, :private_bathroom, :show, :term, :total_rooms, :utilities, :washer_dryer
serialize :term
def listings
#listings ||=find_listings
end
private
def find_listings
listings=Listing.order(:price)
listings=Listing.where("listings.price <= ?", maximum_price) if maximum_price.present?
listings=Listing.where(total_rooms: total_rooms) if total_rooms.present?
listings=Listing.where(available_rooms: available_rooms) if available_rooms.present?
listings=Listing.where(bathrooms: bathrooms) if bathrooms.present?
listings=Listing.where(term: term)
listings=Listing.where(furnished: furnished)
listings=Listing.where(negotiable: negotiable)
listings=Listing.where(utilities: utilities)
listings=Listing.where(air_conditioning: air_conditioning)
listings=Listing.where(parking: parking)
listings=Listing.where(washer_dryer: washer_dryer)
listings=Listing.where(private_bathroom: private_bathroom)
listings
end
end
Here is the show method for filter.
<p id="notice"><%= notice %></p>
<%= render (#filter.listings) %>
Pretty simple.
And here is the template called _listing.html.erb
<div style="padding:5px">
<%= link_to 'New Listing', new_listing_path,{:style=>'', :class => "btn"} %>
<h1>Available Sublets</h1>
<table id="listingTable" class="table table-bordered table-hover">
<tr>
<th><%= link_to 'Filter', new_filter_path,{:style=>'', :class => "btn"} %><%= link_to 'Clear Filter', listings_path, {:style=>'', :class => "btn"} %></th>
<th>Address</th>
<th><u><%= "Price Per Month" %></u></th>
<th>Description</th>
</tr>
<% if #listings !=nil %>
<% #listings.each do |listing| %>
<tr onmouseover="this.style.cursor='pointer';"
onclick="window.location.href = '<%= url_for(:controller => 'listings', :action => 'show', :id=>listing.id) %>' " >
<td><%= image_tag listing.photo.url(:small) %></td>
<td><%= listing.address %></td>
<td>$<%= listing.price %></td>
<td width="40%"><%= listing.description %></td>
</tr>
<% end %>
<% end %>
<% else if #listings==nil %>
<p> Sorry, No Sublets Fit Your Criteria! </p>
<% end %>
</table>
However, the filter never returns any results... I have tested atleast 20 times with queries that should definitely return atleast 1 listing. I feel like I have a naming convention problem but I have never used partials before. any help would be great.
This code:
listings=Listing.where(term: term)
listings=Listing.where(furnished: furnished)
listings=Listing.where(negotiable: negotiable)
listings=Listing.where(utilities: utilities)
listings=Listing.where(air_conditioning: air_conditioning)
listings=Listing.where(parking: parking)
listings=Listing.where(washer_dryer: washer_dryer)
listings=Listing.where(private_bathroom: private_bathroom)
Is not actually filtering listings down further. Basically, it's reassigning listings again and again and again.
If you want to apply successive filters to listings, do this:
listings = Listing.where(term: term)
listings = listings.where(furnished: furnished)
listings = listings.where(negotiable: negotiable)
...

ActiveRecord::RecordNotFound Error in Lynda Rails Training (Ch 9 - Delete/Destroy)

I'm new, so forgive my complete ignorance. I'm on Rails 3.2.3 and am doing the Lynda Ruby on Rails Essentials course. I've completed the chapter listed in the title, but am getting an error page after confirming the delete button. Here is a video to show you the error in action.
I've reviewed the following docs to confirm that I've not made typing errors.
Here is my list.html.erb
<div class="subject list">
<h2>Subjects</h2>
<%= link_to("Add New Subject", {:action => 'new'}, :class => 'action new') %>
<table class="listing" summary="Subject List">
<tr class="header">
<th> </th>
<th>Subject</th>
<th>Visible</th>
<th>Pages</th>
<th>Actions</th>
</tr>
<% #subjects.each do |subject| %>
<tr>
<td><%= subject.position %></td>
<td><%= subject.name %></td>
<td class="center"><%= subject.visible ? 'Yes' : 'No' %></td>
<td class="center"><%= subject.pages.size %></td>
<td class="actions">
<%= link_to("Show", {:action => 'show', :id => subject.id}, :class => 'action show') %>
<%= link_to("Edit", {:action => 'edit', :id => subject.id}, :class => 'action edit') %>
<%= link_to("Delete", {:action => 'delete', :id => subject.id}, :class => 'action delete') %>
</td>
</tr>
<% end %>
</table>
Here is my delete.html.erb
<%= link_to("<< Back to List", {:action => 'list'}, :class => 'back-link') %>
<div class="subject delete">
<h2>Delete Subject</h2>
<%= form_for(:subject, :url => {:action => 'destroy'}, :id => #subject.id) do |f| %>
<p>Are you sure you want to permanently delete this subject?</p>
<p class="reference-name">Subject name: <%= #subject.name %></p>
<div class ="form-buttons">
<%= submit_tag("Delete Subject") %>
</div>
<% end %>
</div>
Here is my subjects_controller.rb
class SubjectsController < ApplicationController
def index
list
render('list')
end
def list
#subjects = Subject.order("subjects.position ASC")
end
def show
#subject = Subject.find(params[:id])
end
def new
#subject = Subject.new
end
def create
# Instantiate a new object using form parameters
#subject = Subject.new(params[:subject])
# Save the object
if #subject.save
# If save succeeds, redirect to the list action
redirect_to(:action => 'list')
else
# If save fails, redisplay the form so user can fix problems
render('new')
end
end
def edit
#subject = Subject.find(params[:id])
end
def update
# Find object using form parameters
#subject = Subject.find(params[:id])
# Update the object
if #subject.update_attributes(params[:subject])
# If save succeeds, redirect to the list action
redirect_to(:action => 'show', :id => #subject.id)
else
# If save fails, redisplay the form so user can fix problems
render('edit')
end
end
def delete
#subject = Subject.find(params[:id])
end
def destroy
Subject.find(params[:id]).destroy
redirect_to(:action => 'list')
end
end
Here is the resulting error page referenced in the video above.
If I can get some help in understanding why I can't get this properly delete the file, that would be great.
I'm sorry, I have never heard of "Lynda Ruby on Rails Essentials course" but I can see from your posted code that your delete form looks totally messed up, you have a form_for but you are using a submit_tag! That doesn't make sense. The problem is that if you look in your log file you will see that the params passed in to the delete action do not include an id therefore when you use #subject = Subject.find(params[:id]) you will get the error you are seeing.
The solution - change the submit_tag to f.submit OR change the form_for to a form_tag and make sure the correct route is called, that way the id should be passed back through the params hash.
Your log file stack trace is ALWAYS your very best friend, learn to understand it ASAP and you will find your life a lot easier.
UPDATE
For a large number of reasons I think your best option would be to change your form to look like this
<%= link_to("<< Back to List", {:action => 'list'}, :class => 'back-link') %>
<div class="subject delete">
<h2>Delete Subject</h2>
<p>Are you sure you want to permanently delete this subject?</p>
<p class="reference-name">Subject name: <%= #subject.name %></p>
<div class ="form-buttons">
<%= button_to "Delete", subject_path(#subject), method: :delete %>
</div>
</div>
The reason the first way did not work is because you missed the leading opening tag "<" which is why the text got displayed instead of the button
you don't need the form, you are entering no data so just use the button_to and tell it to go to the delete action.
I haven't tested the code but it should be fine

Resources