Currently I have the situation that one button is add to the index-form. This workes perfectly in combination with the other functionalties as search and checkboxes which are also part of the index-form.
Code of the index.html.erb:
<%= form_tag order_path, :method => 'get' do %>
<p>
<%= submit_tag "Historical Search", :account_short => nil %>
<%= text_field_tag :search, params[:search] %>
</p>
<% end %>
<%= form_tag sendnext_order_path, :method => :put do %>
<%= submit_tag "Send to Desk" %><br/>
-- other code from index-form
<% end %>
Combined with the controller:
def sendnext
Order.update_all(["status_id = ? ", "2"], :id => params[:order_ids])
redirect_to order_path, notice: 'Order succesfully send to desk.'
end
Now I want to add a second button next to the Send to Desk button with another action than the excisting working one. Until now I'm not capable to realise this.
Please advice. Any feedback is welcome.
Use button_to
<%= button_to('Send to Desk', 'sendnext', :method => "put") %>
<%= button_to('Cancel Order', 'cancelorder ', :method => "put") %>
Will take care of the form for you. submit_tag is submitting the first form I believe.
For example
<%= button_to "New", :action => "new" %>
will generate
# => "<form method="post" action="/controller/new" class="button_to">
# <div><input value="New" type="submit" /></div>
# </form>"
Thanks for your help. I have found a working solution which realised my current requirements:
The index.html.erb looks like the following:
<%= form_tag updateorder_order_path, :method => :put do %>
<%= submit_tag "To Desk" %><br/>
<%= submit_tag "Cancel Order" %>
-- other code like data fields
<%end %>
The controller.rb looks like the following:
def updateorder
if params[:commit] == "To Desk"
Order.update_all(["status_id = ? ", "2"], :id => params[:order_ids])
redirect_to order_path, notice: 'Order(s) successfully send to desk.'
elsif params[:commit] == "Cancel Order"
Order.update_all(["status_id = ? ", "3"], :id => params[:order_ids])
redirect_to order_path, notice: 'Order(s) successfully cancelled.'
else
Order.update_all(["status_id = ? ", "5"], :id => params[:order_ids])
redirect_to order_path, notice: 'Order(s) successfully updated.'
end
end
The routes.rb contains the next code:
resources :orders do
put 'updateorder', :on => :collection
end
Related
I'm am trying to have a form submit to a custom action. The form won't even render, it just displays a error: 'No route matches'".
routes.rb
resources :users do
member do
post :add_foo
end
end
users_controller.rb
def add_foo
puts "!!! in add_new_foo .. params = " + params + " !!!"
end
users/new.html.erb
<%= simple_form_for(#user) do |f| %>
<%= button_to 'download', add_foo_user_path(#user) %>
<% end %>
I have also tried
<%= simple_form_for #user, :url => add_foo_user_path(#user), :method => :post do |f| %>
<%= f.submit "Add" %>
<% end %>
Any help would be appreciated!
Everything is defined correctly. The error is most likely raised because the #user instance is not present.
I want to update an attribute ':what_cause' of model user on a page which is in a session. User clicks on one of the 3 radio buttons and corresponding value should be transferred to a method which updates it.
I wrote following code-
<%= form_for :user do |f| %>
<label>Pratham</label>
<%= f.radio_button :what_cause, "pratham" %>
<label>Kali</label>
<%= f.radio_button :what_cause, "kali" %>
<label>Akshaya</label>
<%= f.radio_button :what_cause, "akshaya" %>
<%= f.submit "Save", :controller => "users_controller", :action => "change_cause", :method => "put" %>
<% end %>
And here is the code for updation in change_cause method of users_controller.rb-
def change_cause
if params[:radio_button] == "pratham"
#user.update_attribute(:what_cause, "pratham")
end
if params[:radio_button] == "kali"
#user.update_attribute(:what_cause, "kali")
end
if params[:radio_button] == "akshaya"
#user.update_attribute(:what_cause, "akshaya")
end
end
But it is not working. Please enlighten me. I am a newbie in RAILS!!!
def change_cause
#user.update_attribute(:what_cause, params[:user][:what_cause])
end
I'm know this is a newbie question just not sure what I'm missing and decided to post hear after my usual search through Google. I'm trying to post content to the database from a form in the footer of the application (for a newsletter) the view is therefore repeated throughout the application. Right now when I submit the form a new object is created in the database but all the fields are "NULL". It seems I need to put the #newsletter variable somewhere, I'm just not sure where.
Partial I'm Rendering in the View
<%= form_tag({:controller => "newsletters", :action => "create"}, :method => "post", :id => "footer_email_form") do %>
<%= text_field_tag :first_name, '', id: "footer_email_firstname" %>
<%= text_field_tag :last_name, '', id: 'footer_email_lastname' %>
<%= text_field_tag :email, '', id: 'footer_email_address' %>
<%= submit_tag "Submit", :name => nil, id: 'footer_email_submit', class: "btn btn-primary" %>
<% end %>
Controller (Create Action)
class NewslettersController < ApplicationController
def create
#newsletter = Newsletter.new(params[:newsletter])
if #newsletter.save
format.html { redirect_to 'pages#home', notice: 'Thank You for signing up for our newsletter' }
format.json { render json: #newsletter, status: :created, location: #newsletter }
else
format.json { render json: #newsletter.errors, status: :unprocessable_entity }
end
end
end
Routes
resources :newsletters, :only => [:create, :destroy]
Use something like this:
<%= form_for Newsletter.new do |f| %>
<%= f.text_field :first_name %>
<%= f.text_field :last_name %>
<%= f.text_field :email %>
<%= f.submit_tag "Submit", class: "btn btn-primary" %>
<% end %>
The way your original form works the params are submitted like this:
params = {
:first_name => 'A',
:last_name => 'B',
:email => 'C',
# and so on...
}
Now if you do #newsletter = Newsletter.new(params[:newsletter]) nothing will happen, because params[:newsletter] is nil and therefore all your attributes are going to be nil (and show up as NULL in the DB).
You should always have an eye on the development log. It's going to help you debug such errors.
I'm relatively new to rails and am trying to pull off my first polymorphic association with comments.
I am running rails 3.2.3
Edit - When I try to post a comment, my log is returning this error:
Started POST "/comments" for 127.0.0.1 at 2012-05-20 13:17:38 -0700
Processing by CommentsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"SOLcF71+WpfNLtpBFpz2qOZVaqcVCHL2AVZWwM2w0C4=", "comment"=>{"text"=>"Test this comment"}, "commit"=>"Create Comment"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = 101 LIMIT 1
Completed 500 Internal Server Error in 126ms
NoMethodError (undefined method `Comment' for nil:NilClass):
app/controllers/comments_controller.rb:13:in `create'
I have tried out many different solutions offered on SO and elsewhere, including the answer from Jordan below, due, I'm sure, to my own inexperience, but have been unable to resolve the error.
The trace calls out line 13 in the Comments Controller and I commented after that line below to mark the error:
class CommentsController < ApplicationController
def index
#commentable = find_commentable
#comments = #commentable.comments
end
def new
#post = Post.find(params[:post_id])
end
def create
#commentable = find_commentable
#comment = #commentable.comments.build(params[:comment]) #<<<<LINE 13
if #comment.save
flash[:notice] = "Successfully created comment."
redirect_to :id => nil
else
render :action => 'new'
end
end
private
def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
end
Posts Controller:
def show
#post = Post.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render :json => #post }
end
end
Comment template (in post show)
<ul id="comments">
<% if #comments %>
<h2>Comments</h2>
<% #comments.each do |comment| %>
<li><%= comment.text %></li>
<% end %>
<% else %>
<h2>Comment:</h2>
<% end %>
</ul>
<%= simple_form_for [#commentable,Comment.new], :html => { :class => 'form-horizontal', :multipart => true } do |f| %>
<fieldset>
<%= f.input :text %>
Upload Photo <%= f.file_field :photo %>
</fieldset>
<div class="form-actions">
<%= f.submit nil, :class => 'btn btn-primary' %>
</div>
<% end %>
Post show:
<p id="notice"><%= notice %></p>
<div class="row">
<div class="span2 offset1">
<%= image_tag #post.photo.url(:show) %>
</div>
<div class="span5">
<h1><%= #post.title %></h1>
<p><%= #post.index_text.html_safe %></p>
<p><%= #post.show_text.html_safe %></p>
<%= render "comments/comment" %>
<%= render "comments/form" %>
<% if can? :update, #course %>
<%= link_to 'Edit Post', edit_post_path(#post), :class => 'btn btn-mini' %>
<%= link_to 'Delete Post', #post,
confirm: 'Are you sure?',
method: :delete,
:class => 'btn btn-mini' %>
<%= link_to 'New Post', new_post_path, :class => 'btn btn-mini' %>
<% end %>
</div>
<nav class="span2 offset1">
<ul class="well">
<li>Category 1</li>
<li>Category 2</li>
</ul>
</nav>
</div>
<div class="row offset2">
<%= link_to 'Back to Posts', posts_path, :class => 'btn btn-mini' %>
</div>
Routes:
resources :posts, :has_many => :comments
resources :comments
It is probably something obvious that someone with more experience can resolve. Let me know if anything comes to mind. Brian
The problem is that #commentable is nil, which means that CommentsController#find_commentable is returning nil. I think your regular expression is sound, so that means one of two things is happening in find_commentable:
There aren't any keys in params that match your regex.
Your regex is matching but there aren't any records in the resulting table with the id in value.
Debug this as usual by inspecting params and the records in your database to make sure they look like you expect them to look.
The problem is your find_commentable method.
Here are the params passed to your CommentsController#create:
Started POST "/comments" for 127.0.0.1 at 2012-05-20 13:17:38 -0700
Processing by CommentsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"SOLcF71+WpfNLtpBFpz2qOZVaqcVCHL2AVZWwM2w0C4=", "comment"=>{"text"=>"Test this comment"}, "commit"=>"Create Comment"}
Here is your CommentsController#create:
def create
#commentable = find_commentable
#comment = #commentable.comments.build(params[:comment]) #<<<<LINE 13
def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
As you can see, find_commentable expects a param like xx_id (for example, comments_id) which it uses to search for an appropriate class (in case of comments_id, it will be Comment), otherwise it returns nil. Refer classify and constantize here.
Your params do not contain any such param. So, you always get a nil object.
Your find_commentable needs some rework. I think in case of nested_fields, it should be an expression like
/(.+)_attributes$/
instead of
/(.+)_id$/.
And you need to have
:accepts_nested_attributes_for :commentable
in your Comment model class.
I tried both of the above answers, but the problem continued.
I ended up consulting with a friend who suggested the following solution, which I like because it's more elegant than my original attempt and easier to read (for later, when I or someone else need to return to the code):
def find_commentable
if params[:post_id]
Post.find(params[:post_id])
#elsif params[:other_id]
# Other.find(params[:other_id])
else
# error out?
end
end
The commented out section will refer to other associations once I get them up and running.
I've installed devise for my rails app, i can go to the sign in page or the sign up page. But I want them both on a welcome page...
So I've made a welcome_page_controller.rb with the following function:
class WelcomePageController < ApplicationController
def index
render :template => '/devise/sessions/new'
render :template => '/devise/registration/new'
end
end
But when i go to the welcome page i get this error:
NameError in Welcome_page#index
Showing /Users/tboeree/Dropbox/rails_projects/rebasev4/app/views/devise/sessions/new.html.erb where line #5 raised:
undefined local variable or method `resource' for #<#<Class:0x104931c>:0x102749c>
Extracted source (around line #5):
2: <% #header_title = "Login" %>
3:
4:
5: <%= form_for(resource, :as => resource_name, :url => session_path(resource_name)) do |f| %>
6: <p><%= f.label :email %><br />
7: <%= f.email_field :email %></p>
8:
Does anybody knows a solution for this problem? Thanks in advance!
Does it have to do with the fact that it is missing the resource function? in the welcome_page controller? It's probably somewhere in the devise controller...?
Regards,
Thijs
Here's how I managed to did it.
I've put a sign up form in my home#index
My files:
view/home/index.html.erb
<%= render :file => 'registrations/new' %>
helper/home_helper.rb
module HomeHelper
def resource_name
:user
end
def resource
#resource = session[:subscription] || User.new
end
def devise_mapping
#devise_mapping ||= Devise.mappings[:user]
end
def devise_error_messages!
return "" if resource.errors.empty?
messages = resource.errors.full_messages.map { |msg| content_tag(:li, msg) }.join
sentence = I18n.t("errors.messages.not_saved",
:count => resource.errors.count,
:resource => resource_name)
html = <<-HTML
<div id="error_explanation">
<h2>#{sentence}</h2>
<ul>#{messages}</ul>
</div>
HTML
html.html_safe
end
end
You need that part because Devise works with something called resource and it should be defined so you can call your registration#new anywhere.
Like that, you should be able to register. However, I needed to display errors on the same page. Here's what I added:
layout/home.html.erb (the layout used by index view)
<% flash.each do |name, msg| %>
# New code (allow for flash elements to be arrays)
<% if msg.class == Array %>
<% msg.each do |message| %>
<%= content_tag :div, message, :id => "flash_#{name}" %>
<% end %>
<% else %>
# old code
<%= content_tag :div, msg, :id => "flash_#{name}" %>
<% end %> #don't forget the extra end
<% end %>
I found this code here
And here's something I created: I saved my resource object if invalid in a session so that the user hasn't to fill every field again. I guess a better solution exists but it works and it's enough for me ;)
controller/registration_controller.rb
def create
build_resource
if resource.save
if resource.active_for_authentication?
# We delete the session created by an incomplete subscription if it exists.
if !session[:subscription].nil?
session[:subscription] = nil
end
set_flash_message :notice, :signed_up if is_navigational_format?
sign_in(resource_name, resource)
respond_with resource, :location => redirect_location(resource_name, resource)
else
set_flash_message :notice, :inactive_signed_up, :reason => resource.inactive_message.to_s if is_navigational_format?
expire_session_data_after_sign_in!
respond_with resource, :location => after_inactive_sign_up_path_for(resource)
end
else
clean_up_passwords(resource)
# Solution for displaying Devise errors on the homepage found on:
# https://stackoverflow.com/questions/4101641/rails-devise-handling-devise-error-messages
flash[:notice] = flash[:notice].to_a.concat resource.errors.full_messages
# We store the invalid object in session so the user hasn't to fill every fields again.
# The session is deleted if the subscription becomes valid.
session[:subscription] = resource
redirect_to root_path #Set the path you want here
end
end
I think I didn't forget any code. Feel free to use whatever you need.
Also, you can add your sign in form in the same page (something like that:)
<%= form_for("user", :url => user_session_path) do |f| %>
<%= f.text_field :email %>
<%= f.password_field :password %>
<%= f.submit 'Sign in' %>
<%= f.check_box :remember_me %>
<%= f.label :remember_me %>
<%= link_to "Forgot your password?", new_password_path('user') %>
<% end %>
Cheers !