Rails: Ajax-enabled form without a model object - ruby

I'm new to Rails and having a hard time figuring out how to create a form that submits over Ajax without having a corresponding model object.
My use case is a simple form that collects an email address and sends it an email; there's nothing to be persisted, so no model.
In cases where I do have a model, I've had success with form_for(#model, remote: true). I can't seem to find the right helper for the case where there is no model. I tried form_tag(named_path, remote: true) and that works, but does not use Ajax.
Pointers to an example with an example with a proper controller, .html.erb and routes.rb would be really appreciated.

Here's how I solved it. The key was using form_tag and specifying a hash with an argument that properly matched my route. For my business logic, I need to pass in an "id" param, which is used in the controller logic.
<%= form_tag(sendmail_path({ id: 1}), remote: true) do %>
<%= text_field_tag :email, params[:email] %>
<%= submit_tag "Send", remote:true %>
<% end %>
routes.rb:
MyApp::Application.routes.draw do
post '/sendmail/:id(.:format)' => 'mycontroller#sendmail', :as => 'sendmail'
# etc...
end
I also had to supply a sendemail.js.erb template which updates the form after submission.

Related

Saving data in ruby on Rails without resources

Its bit difficult for me to explain what I want, but still I will try my best.
I created a form in Rails where user can fill certain fields. Now once these fields are filled, I know that I can use resources in Router and define a create method in Controller that will save the data to database.
However what I want is to pass data saved in the form to my controller. Then create a custom method in controller that will be just like traditional Create method, but instead of passing parameters using Resource method, I want to pass them as parameter. Is it even possible in Rails:
This is my current View to create form:
<h1> Please add a new product</h1>
<%= form_for #product do |p| %>
<p>
<%= p.label 'Product Name' %><br/>
<%= p.text_field :product_name %><br/>
</p>
<p>
<%= p.label 'Description' %><br/>
<%= p.text_area :description %><br/>
</p>
<p>
<%= p.label 'Price' %><br/>
<%= p.text_field :price %><br/>
</p>
<p>
<%= p.label 'Rating' %><br/>
<%= p.text_field :rating %><br/>
</p>
<% end %>
So may be I am using In Built form in Ruby, but I just want to pass parameters from View to Controller's method.
Thanks for help !!!
I will help you in solving your problem.
Follow these steps:
Create your route in routes.rb:
get "/create_product" => 'products#create_product', as: :create_product
or if you want to pass params through post method:
post "/create_product" => 'products#create_product', as: :create_product
Now change your view file according to the new route helper:
form_for (#products, url:{:controller=>'products', :action=>'create_product'}, html:{method:'post'})
Now the last step modify your controller:
def create_product
#your form values are avaible here in params variable
pp params
puts params[:Price]
#save your params into ur db
end
Note: I assumed that you already have product.rb model

redirect to another URL using submit button in ruby

I have submit button and i want to redirect in another URL (hard coded) this URL
https://www.ccavenue.com/shopzone/cc_details.jsp
my code :
<%= form_tag #ccavanue do |f| , url => "https://www.ccavenue.com/shopzone/cc_details.jsp", :html => :method => "put" %>
<%= hidden_field_tag :my_field, #MerchantId, :id => 'merchant_id' %>
<%= submit_tag "Click Me" %>
<% end %>
i want to redirect another website URL with this submit button . please guided me.
Change your code to following:
<%= form_for #ccavanue, url: "https://www.ccavenue.com/shopzone/cc_details.jsp" do |f| %>
<%= f.hidden_field :my_field, #MerchantId, :id => 'merchant_id' %>
<%= f.submit "Click Me" %>
<% end %>
In Rails a form is designed to create or update a resource and reflects the identity of the resource in several ways:
The url that the form is sent to (the form element's action attribute) should result in a request being routed to the appropriate controller action (with the appropriate :id parameter in the case of an existing resource),
Input fields should be named in such a way that in the controller their values appear in the appropriate places within the params hash, and
For an existing record, when the form is initially displayed, input fields corresponding to attributes of the resource should show the current values of those attributes.
In Rails this is achieved by creating form using form_for where:
If we want to create any object we use POST method within url and PUT method if we are trying to update an existing record.
Rails framework is smart enough to use POST or PUT method by itself looking at the url of the form. So in this case we need not use method parameter within form_for url.
Probably you can start with Michael Hartl's tutorial

Rails 4 - Controller Edit Action Returning Wrong Record

I have a Comment model which belongs to both User and Story. Creating a comment correctly associated to the appropriate User and Story is working fine but when trying to edit the comment my edit action appears to retrieving the wrong record.
The offending action in comments_controller.rb:
def edit
#story = Story.find_by(params[:story_id])
#comment = #story.comments.find_by(params[:id])
end
The link used to render the comments/edit view:
<%= link_to 'edit', edit_story_comment_path(comment.story_id, comment.id) %>
The corresponding view:
<%= form_for(#comment, url: { controller: 'comments', action: 'update' }) do |f| %>
<%= f.text_area :content %>
<%= f.submit "update" %>
<% end %>
The edit view appears to be rendering the most recently added comment regardless of which #comment I am trying to edit.
You're using find_by, which is basically a magic find_by_X method, with no fields specified. find_by(1) generates invalid SQL for me using Postgres, but it might be that whatever database back-end your using accepts it.
Regardless, find_by certainly won't do what you want it to do.
You should be using find, if you want to find records by id:
#story = Story.find(params[:story_id])

removing a document by passing its id using form_tag

Let's say I have book model, book.rb
class Book
include Mongoid::Document
field :book_id, type: String
field :title, type: String
end
(Here I'm using mongoid, but I think for this question it doesn't matter what type of data is.)
The book model has its own controller, views, etc.
Now, I want to create a page with form_tag (let me know if this is not a proper way), where by entering book's id and clicking enter I'll be able to remove the record this this given id from the database.
remove.html.erb:
<%= form_tag books_path, :method => 'get' do %>
<p>book_id:
<%= text_field_tag :book_id, params[:book_id] %>
<%= submit_tag "Remove", :name => nil, :confirm => "Are you sure?" %>
</p>
<% end %>
I know how to remove a given document, but can't figure out how to pass the value entered in the form and where to put the logic that will remove document.
First things first. Why do you need to store a book_id for your Book model ? Mongoid already provide a _id field for this purpose.
The usual way to destroy resources is to hit the destroy action in your controller by making a DELETE HTTP request.
class BooksController
def destroy
Book.find(params[:id]).destroy
redirect_to :back
end
end
Then simply do a link with the following:
link_to "Delete", book_path(#book), method: :delete
Where #book is your book instance.

Rails3 routing error with ajax

UPDATED CODE at the bottom
I am creating a story voting app via Simply Rails 2 book. I am getting this error when I click the button to vote up a story:
No route matches "/stories/4-pure-css-icons-showcase"
My routing file looks like this:
Shovell::Application.routes.draw do
get "votes/create"
root :to => "stories#index"
resources :stories do
resources :votes
end
end
votes_controller.rb:
class VotesController < ApplicationController
def create
#story = Story.find(params[:story_id])
#story.votes.create
end
end
create.rsj :
page.replace_html 'vote_score', "Score: #{#story.votes.size}"
page[:vote_score].visual_effect :highlight
show.html.erb:
<h2>
<span id="vote_score">
Score: <%= #story.votes.size %>
</span>
<%= #story.name %>
</h2>
<p>
<%= link_to #story.link, #story.link %>
</p>
<div id="vote_form">
<%= form_tag :url => story_votes_path(#story), :remote => true do %>
<%= submit_tag 'shove it' %>
<% end %>
</div>
story.rb :
class Story < ActiveRecord::Base
validates_presence_of :name, :link
has_many :votes
def to_param
"#{id}-#{name.gsub(/\W/, '-').downcase}"
end
end
I've been working through a number of other errors before this having to do with deprecated code and so forth, so I feel somewhat lost at the moment. It seems like it should just be a routing a issue, but since I've been working through AJAX errors that also have to do with the vote function I wanted to post those files just in case it was more than routing.
It says no route matches "/stories/4-pure-css-icons-showcase" but when I visit "/stories" (my root) and click on the link to take me to "/stories/4-pure-css-icons-showcase" it works fine, however after clicking on the vote button I get this error. As you could probably tell after reading the code, it is suppose to update the vote count and do a :highlight via ajax.
UPDATE:
Changed code (all changes are per Sam's advice):
routes:
Shovell::Application.routes.draw do
resources :votes
root :to => "stories#index"
resources :stories do
resources :votes
end
show.html.erb:
<div id="vote_form">
<%= form_tag :url => new_story_vote_path(#story), :remote => true do %>
<%= submit_tag 'shove it' %>
<% end %>
</div>
votes_controller.rb
class VotesController < ApplicationController
def create
#story = Story.find(params[:story_id])
#story.votes.create
respond_to do |format|
format.html
format.js
end
end
The problem is still exactly the same, but I think (read: hope) we are making progress!
The scenario: My index (/stories) page randomly displays a story from the database, when you click the link it takes you to the story's internal page (ex. /stories/2-sitepoint-forums) on this page it displays the number of votes the story has and has a button to vote for it. When you click the vote button it is suppose to use ajax to update the #story.vote.size and use a :highlight visual effect. However, the problem is that when you click the vote button the page changes to a "Routing Error" page which displays:
No route matches "/stories/2-sitepoint-forums"
Its weird to me because you can in fact be routed to that address and you are from the link on the first page...
Here is the error in the console:
Started POST "/stories/2-sitepoint-forums?url=%2Fstories%2F2-sitepoint-forums%2F
votes%2F2-sitepoint-forums&remote=true" for 127.0.0.1 at 2010-11-08 16:30:17 -08
00
ActionController::RoutingError (No route matches "/stories/2-sitepoint-forums"):
Rendered C:/Ruby192/lib/ruby/gems/1.9.1/gems/actionpack-3.0.0.rc2/lib/action_dis
patch/middleware/templates/rescues/routing_error.erb within rescues/layout (1.0m
s)
Im not sure if this is any more telling, but I thought I'd add it incase.
New:
I have not been able to solve this problem as of yet. Because I still don't feel like I completely understand the issue I have decided to move over to the Ruby on Rails 3 Tutorial Book online and see if I can't figure it out while working through it. Since I was planning to do it next anyway (I have plans to combine both apps later) it appears now is the time.
<%= form_tag :url => new_story_vote_path(#story), :remote => true do %>
<%= submit_tag 'shove it' %>
<% end %>
That should send it to the create action.
def create
#story = Story.find(params[:story_id])
#story.votes.create
respond_to do |format|
format.html
format.js
end
end
And that should take care of your ajax.
take this get "votes/create" out of your routes
and add this
map.resources :votes
I'm not familiar with using form_tag and :remote (as I normally just write jQuery for stuff like this) but a couple of things definitely pop out at me with what you're doing here that may help you resolve the issue.
First of all, I think you can rework the way you set up a vote and thus the way you set up the form for the vote. In the stories controller, for the show action, I'd set up the vote right away:
#vote = Vote.new(:story_id => #story.id)
This lets you set up your form as so:
= form_for(#vote), :remote => true do |f|
= hidden_field f.story_id
= submit_tag "Vote"
This is both a cleaner way of doing things, in my opinion, but also may fix the general issue you are dealing with, because you are now passing data with the form (the hidden field) in your POST request. Rails will behave unexpectedly if you perform AJAX POST requests that do not actually submit data.
In other words, your original form is likely running as an AJAX POST request but it would have worked better as an AJAX GET request, since it is not actually submitting data, it is simply "hitting" an URL.
I am not sure if you found the answer to your problem yet, but I wanted to post for others that may be looking for an answer similar to yours.
The code:
<%= form_tag :url => new_story_vote_path(#story), :remote => true do %>
<%= submit_tag 'shove it' %>
<% end %>
will result in /stories/:story_id/votes/new url with a :post request. It won't work because the new route is a :get method request. If you wanted to go to the new method, you'll need to tell the form to use the get http method.
<%= form_tag :url => new_story_vote_path(#story), :remote => true, :html => { :method => :get } do %>
<%= submit_tag 'shove it' %>
<% end %>
However, I think that you are wanting to route to the create method in your controller. I would do something like:
<%= form_tag :url => story_votes_path(#story), :remote => true do %>
<%= submit_tag 'shove it' %>
<% end %>
This should route correctly to the create method in your VotesController.

Resources