HTML creating href in wrong order for rails route - html

I am using link_to to try to delete a record, but I'm getting an error saying the delete path does not exist. When looking at the href in the html form, the href is in the form of :id/controller instead of controller/:id. I have two examples of this, one for Edit that seems to work as expected, and one for Remove, where the route seems to be off. The main difference I see is that locale is not being defined on the destroy href. Any ideas on what is causing this issue? I saw this before on a different form, but I am starting to see this much more often. Any help would be much appreciated.
Routes:
topdressings GET (/:locale)/topdressings(.:format) topdressings#index {:locale=>/en|es/}
POST (/:locale)/topdressings(.:format) topdressings#create {:locale=>/en|es/}
new_topdressing GET (/:locale)/topdressings/new(.:format) topdressings#new {:locale=>/en|es/}
edit_topdressing GET (/:locale)/topdressings/:id/edit(.:format) topdressings#edit {:locale=>/en|es/}
GET (/:locale)/topdressings/:id(.:format) topdressings#show {:locale=>/en|es/}
PATCH (/:locale)/topdressings/:id(.:format) topdressings#update {:locale=>/en|es/}
PUT (/:locale)/topdressings/:id(.:format) topdressings#update {:locale=>/en|es/}
DELETE (/:locale)/topdressings/:id(.:format) topdressings#destroy {:locale=>/en|es/}
HTML:
<td><%= link_to t(:edit), edit_topdressing_path(topdressing), data: { toggle: "modal", target: "#EditModal_#{topdressing.id}", remote: edit_topdressing_path(topdressing) + "#modal-edit-form" }, remote: true %>
|
<%= link_to t(:remove), topdressings_path(topdressing), method: :delete, data: { confirm: t(:confirm_remove_topdressing, device: "#{topdressing.topdressing_device.name}", date: "#{topdressing.date}") } %></td>
HREF DETAILS IN PAGE SOURCE
<td><a data-toggle="modal" data-target="#EditModal_1" data-remote="/en/topdressings/1/edit#modal-edit-form" data-remote="true" href="/en/topdressings/1/edit">Edit</a>
|
<a data-confirm="Are you sure you want to delete the record for Device 2 on 2016-02-26" rel="nofollow" data-method="delete" href="/1/topdressings"><span>Remove</span></a></td>
ERROR ON DELETE:
Started DELETE "/1/topdressing" for 127.0.0.1 at 2016-03-05 14:34:06 -0800
ActionController::RoutingError (No route matches [DELETE] "/1/topdressing"):
web-console (2.0.0.beta3) lib/action_dispatch/debug_exceptions.rb:22:in `middleware_call'
HTML FORM details:

Your second link uses the topdressing_path URL helper and passes it one argument:
link_to t(:remove), topdressings_path(topdressing), method: :delete
But your rake routes shows that path only has one placeholder in it, for the locale:
topdressings GET (/:locale)/topdressings(.:format)
You need to use another URL helper instead. In Rails' resourceful routes you'd have a topdressing_path that you could use:
link_to t(:remove), topdressing_path(topdressing), method: :delete
But I'm guessing that's not how you've got your routes set up. Chances are, you've got something like this in config/routes.rb. You can add an as option to give that route a name, allowing you to use it in your link_to helpers in your views:
scope "(:locale)", locale: /en|nl/ do
# Other routes omitted
get "topdressings/:id", to: "topdressings#show", as: "topdressing"
end

Related

For loops in ejs

I have a array containing some html content like this.
const articleArray=['<p>first text</p>\r\n','<p>second text></p>\r\n','<p>third text</p>\r\n']
I need to render this in an ejs file through a get request
request.render('viewArticles',{array : articleArray})
where 'viewArticles' is an ejs file. I have used the middleware to set the view engine as ejs.
This is the code in ejs
<% for(arr in array) {%>
arr
<% } %>
I am not able to render any html. How to solve this?
'<%- %>' this is help to print html code as it is.
<% 'Scriptlet' tag, for control-flow, no output
<%_ ‘Whitespace Slurping’ Scriptlet tag, strips all whitespace before it
<%= Outputs the value into the template (HTML escaped)
<%- Outputs the unescaped value into the template
<%# Comment tag, no execution, no output
<%% Outputs a literal '<%'
%> Plain ending tag
-%> Trim-mode ('newline slurp') tag, trims following newline
_%> ‘Whitespace Slurping’ ending tag, removes all whitespace after it
for refrence please click visit this site EJS
<% array.forEach(function(item) {%>
<%-item%>
<% }) %>
Try this
<% array.forEach(function(item,index){ %>
<%= item %>
<% }) %>
I'm not really sure how to do what you want exactly , but take a look at this:
First, instead of you creating an array of HTML elements, how about you create an array of objects, like so :
const articles = [{text: "first text"} , {text: "second text"}, {text: "third text"}];
this way you just have to write the HTML once, and I am fairly new to programming but I don't see a scenario where you would get a response in HTML, usually you query a database for data or from a JSON file... and assuming the array is actually getting passed to the .ejs file, lets iterate though it,
<% for(let a of articles){ %>
<p> <%= a.text %> </p>
</br>
<% } %>
If the array is NOT getting passed, check for these in your code :
// If you installed
..."dependencies" : {
"ejs": "x.x.x",
} //Check the package.json file
// If you imported correctly
import ejs = require("ejs");
// If you specified the views path
app.set("views", path.join(__dirname, "views"));
// And the views engine
app.set("view engine", "ejs");
// And your route
request.render('viewArticles',{ articles : articles }) // Check if the file name is correct, I get this wrong many times

The "show" page isn't displaying the property of the correct data

I'm making a website using ror and I have a list of fandoms, and I want to display different pictures and writing for that fandom. Right now, just for testing, I'm having it just display the name of the fandom at the top of the page, but no matter which one I click on, it only displays the name of the first fandom. Here's the parts of the files I think are relevant, but if you need to see more, I'll post it.
Section of routes.rb:
get 'fandoms' => 'fandoms#index'
get 'fandoms/new' => 'fandoms#new'
post 'fandoms' => 'fandoms#create'
get 'fandoms/:id' => 'fandoms#show', as: :fandom
resources :fandoms
The show method in fandoms_controller:
def show
#fandom = Fandom.find_by(params[:id])
end
The index.html.erb for fandoms:
<div class="main">
<div class="container">
<h2>Fandoms</h2>
<%= link_to "New Fandom (dev only)", "fandoms/new" %>
<% #fandoms.each do |fandom| %>
<div class="fandoms">
<%= link_to fandom.name, fandom_path(fandom) %>
</div>
<% end %>
</div>
And finally the show.html.erb for fandoms:
<div class="main">
<div class="container">
<h2>Fandoms</h2>
<div class="fandom">
<h1><%= #fandom.name %></h1>
</div>
</div>
</div>
I double checked my code with the Ror tutorial on codecademy, but I still couldn't find any differences for what I wanted to do.
Thanks.
Your show action has a subtle typo that's breaking your logic:
#fandom = Fandom.find_by(params[:id])
Should actually be:
#fandom = Fandom.find(params[:id])
The difference is, find_by will return the first row for which the conditions passed are met. You're not actually passing any conditions; just an ID, which in Postgres doesn't even work:
irb> Fandom.find_by(1)
PG::DatatypeMismatch: ERROR: argument of WHERE must be type boolean, not type integer
LINE 1: SELECT "fandoms".* FROM "fandoms" WHERE (1) LIMIT 1
Your database is more permissive, but seems to be treating it just as a WHERE TRUE clause and thus every single row meets the condition. As such, it returns the first row every time. Using find(id) will give you the desired result.

Sending <input type="image"> to a folder on the server

I have this code
<%= form_for(:img, url: {action: "postodb"}) do |f| %>
<div id="image-preview">image here!</div>
<%= f.submit "Send to database" %>
<%end%>
Here <input type="image"> is added from a js file
var imageDiv = $("#image-preview");
imageDiv.html('<input type="image" name="img1" style="margin-left:146px"id="spiro-img" src="'+img+'"/>');
This all works fine..
Next I want to send this to the folder but it doesnt work
This is the code I have in the controller(referred from this site http://rohitrox.github.io/2013/07/19/canvas-images-and-rails/)
def postodb
data = params[:data_uri]
image_data = Base64.decode64(data['data:image/png;base64,'.length .. -1])
File.open("/public/uploads/somefilename.png", 'wb') do |f|
f.write image_data
end
end
This is the error I get
Plz help.
Using carrierwave gem for loading images.
First what your should to do is read a docs: http://www.w3schools.com/Tags/att_input_type.asp
image - Defines an image as the submit button.
Second what your should learn to read is logs. At screenshot you have section with params, and there is no data_uri key.
And finaly use the <input type='file' ... /> for upload. If you want beauty async upload with preview, you should look on jquery-file-upload gem instead.
P.S.: type='image' is a submit button with image.

How can I save each item in a "select multiple" field in its own MySQL record (using Rails)?

Thanks for any help you can provide! I have a Ruby on Rails application where I am trying to save maps with driving directions and waypoints. The data needs to come straight out of the entry form instead of the Google Maps javascript. I've solved the starting and ending points, but the waypoints are giving me a problem.
My questions:
How can I save each waypoint in its own record in the Waypoint table? I'm able to get the first waypoint into the table, but the rest of the "select multiple" options are ignored.
How can I make each waypoint.newsavedmap_id field the same as its corresponding newsavedmaps id so that I can call these up later?
HTML
<p>Enter a street address, city, and state:
<input id="startinput" type="text" name="starthere" size="56"></p>
<p>Or, select a location from the list:
<select id="startdrop" name="startthere">
<option value="">
<% for masterlocation in #masterlocation %>
<option value="<%= masterlocation.street_address %> <%= masterlocation.city %>, <%= masterlocation.state %>, <%= masterlocation.zip %>"><%= masterlocation.place_name %></option>
<% end %>
</select></p>
<div><b>Stops</b></div>
<div id="multiselectdiv1">
<select multiple id="waypoints" name="waypointsselected">
<% for masterlocation in #masterlocation %>
<option value="<%= masterlocation.street_address %> <%= masterlocation.city %>, <%= masterlocation.state %>, <%= masterlocation.zip %>"><%= masterlocation.place_name %></option>
<% end %>
</select>
</div>
<b>End</b>
<p>Enter a street address, city, and state:
<input id="endinput" type="text" name="endhere" size="56"></p>
<p>Or, select a location from the list:
<select id="enddrop" name="endthere">
<option value="">
<% for masterlocation in #masterlocation %>
<option value="<%= masterlocation.street_address %> <%= masterlocation.city %>, <%= masterlocation.state %>, <%= masterlocation.zip %>"><%= masterlocation.place_name %></option>
<% end %>
</select></p>
</div>
<div>
<input type="submit" onclick="calcRoute();" id="showmapview" value="Show Map">
</div>
I have two MySQL tables. The first is newsavedmaps:
id
itinerary_id
start
start_lat
start_long
start_masterlocation_id
end
end_lat
end_long
end_masterlocation_id
name
The second is waypoints:
id
newsavedmap_id
waypoint
waypoint_lat
waypoint_long
waypoint_masterlocation_id
The two are meant to be connected by newsavedmaps.id and waypoint.newsavedmap_id .
My newsavedmap_controller.rb includes:
def create
#newsavedmap = Newsavedmap.new(params[:newsavedmap])
#newsavedmap.name = params[:newsavedmapname]
if !params[:starthere].blank?
#newsavedmap.start = params[:starthere]
else
#newsavedmap.start = params[:startthere]
end
if !params[:endhere].blank?
#newsavedmap.end = params[:endhere]
else
#newsavedmap.end = params[:endthere]
end
if !params[:waypointsselected].blank?
#waypoint = Waypoint.new(params[:waypoint])
#waypoint.waypoint = params[:waypointsselected]
end
Edit 1
In response to Colinm's suggestion to wrap the controller in an iterator to get separate records for each address, I tried this, but I'm pretty sure I'm doing the wrong thing:
if !params[:waypointsselected].blank?
for waypoint in #waypoint
#waypoint = Waypoint.new(params[:waypoint])
#waypoint.waypoint = params[:waypointsselected]
#waypoint.newsavedmap = #newsavedmap
end
end
How can I save each waypoint in its own record in the Waypoint table? I'm able to get the first waypoint into the table, but the rest of the "select multiple" options are ignored.
Unless you have a really good reason not to, use Rails' form helpers instead of rolling your own form fields. They will take care of this automatically, as well as handle edge cases you may not even know about. (Like the gotcha that sending a multiple select back with no selections will leave the record unchanged. That doesn't sound like it's an issue in your use case, but Rails still has your back if you use the form helpers.)
In your case, you'd simply pass multiple: true in the html_options hash, like so:
<%= f.select :waypointsselected,
MasterLocation.waypoints_for_select,
{},
{ multiple: true }
%>
Note that this does assume you implement a waypoints_for_select method. Without seeing all the code, it looks like you have way too much logic in your view right now. It's brittle and verbose to construct the options array in the view; offloading that to the model or a helper keeps your view code cleaner and helps eliminate potential future bugs.
If you absolutely can't/absolutely don't want to use form helpers in this application, the key you're looking for is []. Rails sensibly assumes a form field represents a single value unless you explicitly denote it as an array. Just tack an empty array on the end of the field name:
<select multiple id="waypoints" name="waypointsselected[]">
...and that field's key in the params hash will instead contain an array of values representing the selected items:
{ waypointsselected: ["3", "6", "9"] }
As for associating the waypoints with the newsavedmaps, just set it explicitly during creation. You're almost there:
if !params[:waypointsselected].blank?
#waypoint = Waypoint.new(params[:waypoint])
#waypoint.waypoint = params[:waypointsselected]
# You can do it like this...
#waypoint.newsavedmap = #newsavedmap
# Or using the ID...
#waypoint.newsavedmap_id = #newsavedmap.id
end
(I haven't adapted this code to deal with the fact you now have an array of values in waypointsselected; I just plugged the relationship definitions into your existing code. Remember to adjust your code to expect an array and iterate over it.)

Rails: Adding an empty tag plus content to link_to

I'm trying to generate a link using the link_to helper that will output the following HTML:
<i class="some_class"></i>Link Name
However the code I'm using to try to accomplish this:
link_to(tag("i", class: options[:icon]) + title, url)
...is outputting:
<i class="some_class">Link Name</i>
Why is it doing this, and how can I fix it? Thanks.
EDIT:
I believe I found the issue.
<i> tags are not self-closable tags in HTML5. Therefore the text after the i is treated as that element's content.
Have you tried using the block format of link_to?
<%= link_to url do %>
<%= tag("i", class: options[:icon]) %>
Link Name
<% end %>
Tweak that to your needs and maybe you'll get what you're looking for.
This is the icon tag helper I use in my applications which I frequently pass as the first argument to link_to, which can either be used to create a icon tag alone, or an icon tag followed by text.
def icon_tag(icon, *args)
options = args.extract_options!
text = args.first || options.delete(:text)
if text.nil?
content_tag :i, "", class: ["icon", "icon-#{icon}"] + options[:class].to_a
else
"#{icon_tag icon} #{text}".html_safe
end
end