Rails REST doesn't show/load the right page - Ruby on Rails - ruby-on-rails

Basically I created a controller, model and view for subjects. Basically I have 6 actions inside my controller and set up a REST inside my routes file to route the right file.
When I entered, http://localhost:3000/subjects/index it shows me the view for show.html.erb instead of the index.html.erb
Here's what my subject controller looks like:
class SubjectsController < ApplicationController
def index
#subjects = Subject.sorted
end
And here's the content of my index.html.erb file.
<% #page_title = "All Subjects" %>
<div class="subjects index">
<h2>Subjects</h2>
<%= link_to("Add New Subject", new_subject_path, :class => "action_new") %>
<table class="listing" summary="Subject list" border="1">
<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"><%= status_tag(subject.visible) %></td>
<td class="center"><%= subject.pages.size %> </td>
<td class="actions">
<%= link_to("View Pages", pages_path(:subject_id => subject.id), :class => 'action show') %>
<%= link_to("Show", subject_path(subject), :class => 'action show') %>
<%= link_to("Edit", edit_subject_path(subject), :class => 'action edit') %>
<%= link_to("Delete", delete_subject_path(subject), :class => 'action delete') %>
<td>
</tr>
<% end %>
<table>
</div>
Also here's what I set up on my routes:
resources :subjects do
member do
get :delete
end
end
Any idea what am I missing?

The answer is simple: in order you access the index page, you need to hit the following URL:
http://localhost:3000/subjects
Obviously, it will be with GET
The reason why you got the error is: since, anything of the format subjects/:id will take you to the show action within SubjectsController, so Rails interprets subjects/index as you are trying to access the page subjects/:id with index as id of the subject. Here's nothing wrong with Rails, since in RESTful web services, you access the index page by ONLY using the plural name of the resource, like in your case http://localhost:3000/subjects

Related

Rails 5 ActiveRecord Update Serialized Array in Form

I have a field that is a serialized array. It's loaded into my model and accessed in a form:
class Site < ApplicationRecord
serialize :steps, Array
end
<table class="listing" summary="Site list">
<tr class="header">
<th>Name</th>
<th>Step 1</th>
<th>Step 2</th>
<th>Step 3</th>
<th>Actions</th>
</tr>
<% #sites.each do |site| %>
<tr>
<td><%= site.name %></td>
<% site.steps.each do |step| %>
<td><%= step %></td>
<% end %>
<td class="actions">
<%= link_to("Show", site_path(site), :class => 'action show') %>
<%= link_to("Edit", edit_site_path(site), :class => 'action edit') %>
<%= link_to("Delete", delete_site_path(site), :class => 'action delete') %>
</td>
</tr>
<% end %>
</table>
I'm trying to update my edit form so that I can edit each "step" in the array.
<%= form_for(#site) do |f| %>
<table summary="Site form fields">
<tr>
<th>Name</th>
<td><%= f.text_field(:name) %></td>
</tr>
<% a=1 %>
<% #site.steps.each do |step| %>
<tr>
<th>Step <%= a %>
<td><%= text_field :site, :steps, :value => step %></td>
<% a += 1 %>
</tr>
<% end %>
</table>
<div class="form-buttons">
<%= f.submit("Update Site") %>
</div>
<% end %>
The edit form displays the steps field correctly as each individual string in the array. However, when I attempt to submit the form I get the following error:
Attribute was supposed to be a Array, but was a String.
So steps is being submitted as the last entry in the array. How can I display the form correctly and also present the updated array back to the controller for processing?
Your text_field would need to multiple set to true. I believe in your case, something like this should work.
<%= f.text_field(:steps, { multiple: true, value: #site.steps[step] }) %>

Rails 5 edit multiple not showing values in table

I am creating multiple edit on my app. I have followed the revised Rails screencast and this code that adapts it to Rails 5.
In my Categories Controller:
def edit_multiple
#categories = Category.where(ID: params[:category_ids])
redirect_to categories_url
end
In my index:
<table class="table" summary="Category list">
<tr class="header">
<th style="text-align: left"><%= sort_link(#q, :NAME, 'NAME', default_order: :desc) %></th>
<th style="text-align: left">POSITION</th>
<th style="text-align: left">ACTIONS</th>
</tr>
<%= render "list" %>
</table>
<%= submit_tag "Edit Checked" %>
In my list partial:
<% form_tag edit_multiple_categories_path, method: :get do %>
<% #categories.each do |category| %>
<tr class="<%= cycle('odd', 'even') %>">
<td><%= check_box_tag "category_ids[]", category.ID %></td>
<td><%= link_to category.NAME, {:action => 'show', :ID => category.ID} %>
<td><%= category.RANK_POSITION %></td>
<td class="actions">
<%= link_to("Edit", {:action => 'edit', :ID => category.ID}, :class => 'button tiny') %>
<%= link_to("Delete", {:action => 'delete', :ID => category.ID}, :class => 'alert button tiny') %>
</td>
</tr>
<% end %>
<% end %>
When I open the categories page, it doesn't show anything from _list partial. There's only table headers and Edit Checked button.
Before adding the code relative to multiple edits the table was showing values from partial.
Note that db column names are capital as I'm building the app on existing db.
How can I fix it?
The problem was simply that
<% form_tag edit_multiple_categories_path, method: :get do %>
should be:
<%= form_tag edit_multiple_categories_path, method: :get do %>
I copied that from the railscast #165
Perhaps someone will find same issue and will find this useful.

Rails search table clickable link

I have a keyword search page for which the results are presented in a table. One of the fields in this table is a url which I want to display as a clickable link when the field has one in it but I can't get this working, when the link is clicked it instead queries the search again. I think the problem is due to the def within the searches controller dealing with the keywordsearch view. Can anybody help?
Below is the keywordsearch view which contains the results table:
<!-- Index of all Courses -->
<% provide(:title, "Courses Page") %>
<!--Breadcrumbs -->
<br>
<%= link_to "Back", :back %><br><br>
<!--Page Contents -->
<div class ="row">
<h1>Degrees Offered</h1>
<%= image_tag "line.png" , :alt => "line break"%>
</div>
<div class ="row">
<!-- Form for Keyword Search, to query database for University courses. It is hidden so as to not appear as a search on the page -->
<div class = "hidden">
<%= form_tag(keywordsearch_path, :method => "get", id: "search-data") do %>
<%= text_field_tag :search, params[:search], placeholder: "Search course" %>
<%= submit_tag "Search" %>
<% end %>
</div>
<% if #search_degree != nil %>
<% end %>
<% if #search_degree != nil %>
<table border="1" class="table">
<thead>
<tr>
<th>University Name</th>
<th>Course Name</th>
<th>Duration</th>
<th>Qualification</th>
<th>Entry Requirements</th>
<th>Course Page</th>
</tr>
</thead>
<tbody>
<% #search_degree.each do |degree| %>
<tr>
<td><%= degree.uname %></td>
<td><%= degree.cname %></td>
<td><%= degree.duration %></td>
<td><%= degree.qualification %></td>
<td><%= degree.entry %></td>
<td> <a href=<% degree.url %>>View course page on University Website</a></td>
</tr>
<% end %>
</tbody>
</table>
<% end %>
</div>
Below is portion of the search controller in which keyword search is defined:
def keywordsearch
#search = Degree.all.select(:uname, :cname, :ucas, :duration, :qualification, :entry).distinct.order(id: :ASC)
if params[:search]
#search_degree = Degree.search(params[:search]).order('uname ASC')
end
end
The link from all of this is clickable but rather than taking me to the correct url it redoes the search.
try this instead of hardcoding the <a> tag:
<%= link_to 'View course page on University Website', degree.url %>
Can you also post a sample of url? Be sure to include the protocol (e.g, http://...)

ROR build inserting mutiple records at a time by form

Form screenshot
the image up explain that there is employ who has been allocated three projects at this time he want to full up the fields as he want example he can fill up 2 fields and press submit btn or 1 or 3 depending how many projects he has been assigned.
what i was unable to do is that i want to insert that multiple fields in a table in single submit i do not understand what code i write it will work
the code in my controller is the following.
def new
#pro=Employee.find(params[:employee_id])
#timesheet=Timesheet.new
#project=Project.where(:employee_id => params[:employee_id]).sorted
end
def create
#pro=Employee.find(params[:employee_id])
#timesheet=Timesheet.new(params.require(:timesheets).permit(:employee_id,:project_id,:IN,:comments))
if #timesheet.save
flash[:notice] = "data entered."
redirect_to(:action => 'show',:employee_id =>#pro.id)
else
flash[:notice]="logged out"
end
end
the code in my new.html.erb is the following
<%= form_for(:timesheets, :url => {:action => 'create',:employee_id => #pro.id}) do |d| %>
<% if !#project.nil? %>
<% #project.each do |page| %>
<tr>
<%= d.hidden_field("employee_id" ,:value => #pro.id) %>
<%= d.hidden_field("project_id" ,:value => page.id) %>
<% if !page.employee_id.blank? %>
<td><%= page.prog_name %></td>
<td><%= d.text_field("IN",:class => "qty1") %></td>
<td><%= d.text_field("comments") %></td>
<% end %>
<% end %>
</tr>
<% end %>
<tr>
<td>Total hours</td>
<td colspan="2"><%= text_field_tag("total")%></td>
</tr>
<tr border="0">
<td ><%= submit_tag("Submit") %></td>
<td colspan="2" border="0"></td>
</tr>

How to Correctly render partial template in Rails?

I have a Listing model that I am using to represent a listing for a sublet (apartment), and I created a Filter model as a way for a user to filter listings to his liking. Here in my Filter class, that has a method listings to query listings based on a form submission.
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=listings.where("listings.price <= ?", maximum_price) if maximum_price.present?
listings=listings.where(total_rooms: total_rooms) if total_rooms.present?
listings=listings.where(available_rooms: available_rooms) if available_rooms.present?
listings=listings.where(bathrooms: bathrooms) if bathrooms.present?
listings=listings.where(term: term)
listings=listings.where(furnished: furnished)
listings=listings.where(negotiable: negotiable)
listings=listings.where(utilities: utilities)
listings=listings.where(air_conditioning: air_conditioning)
listings=listings.where(parking: parking)
listings=listings.where(washer_dryer: washer_dryer)
listings=listings.where(private_bathroom: private_bathroom)
listings
end
end
In order to show these, I created a show method for filter that I want to render a partial template. This is what I currently have, but it won't render the template I created called _listings.html.erb in /listings
<p id="notice"><%= notice %></p>
<%= #filter.listings.size %>
<%= render #filter.listings %>
And here is the template
<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>
I think my naming conventions are messed up, but I can't find the correct way to do this. Anyone have any suggestions. Also, the filter always seems to come up empty. I've tested it many times with simple filters but it never works. If anyone sees an error in my filter feel free to point it out. Thanks!
If you call render and pass it an array or relation, it will actually call the singular version on the partial. When you call
<%= render #filter.listings %>
What it ends up doing is equivalent the following:
<%= render :partial => 'listings/listing', :collection => #filter.listings %>
which is equivalent to
<% #filter.listings.each do |listing| %>
<%= render listing %>
<% end %>
Also, there is an error in or partial around the `<% end %> <% else if ... %>, it should be the following
<% 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 %>
<% else %> (since you already checked if it was nil, you it is implied at this point the value is nil
<p> Sorry, No Sublets Fit Your Criteria! </p>
<% end %>
I would recommend writing it the following way, as it is more Ruby-esque
<% if #listings.blank? %>
<p> Sorry, No Sublets Fit Your Criteria! </p>
<% else %>
<% #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 %>
The way I would ultimately handle this case is the following:
Your Filter show view
<p id="notice"><%= notice %></p>
<%= #filter.listings.size %>
<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>
<%= render(#filter.listings) || "<p> Sorry, No Sublets Fit Your Criteria! </p>".html_safe %>
</table>
Your 'listings/_listing.html.erb'
<tr onmouseover="this.style.cursor='pointer';"
onclick="window.location.href = '<%= url_for(listing) %>' " >
<td><%= image_tag listing.photo.url(:small) %></td>
<td><%= listing.address %></td>
<td>$<%= listing.price %></td>
<td width="40%"><%= listing.description %></td>
</tr>

Resources