Devise after_sign_up_for path not working - ruby-on-rails

I read all the thread on this, but I still can't figure out what is wrong. I have gone through all the devise implementation guides and followed them but after a new user registration, the redirect goes to the users controller, specifically users#show.
The initial call to a new registration is going through my registrations controller. That has been verified. But after the registration it doesn't pass through the registrations controller again. It goes through the users controller. I put a break in the two overriding methods in the new registrations controller and they never hit.
/routes.rb
Rails.application.routes.draw do
root to: 'app#index'
devise_for :users, controllers: { registrations: "registrations" }
resources :users do
member do
put 'follow', to: 'users#follow'
put 'unfollow', to: 'users#unfollow'
end
end
end
registrations_controller.rb
class RegistrationsController < Devise::RegistrationsController
protected
#call for new registration does pass through here
#after new registration does not pass through here
def after_inactive_sign_up_path_for(resource)
#never gets here after new registration
other_path(resource)
end
def after_sign_up_path_for(resource)
#never gets here after new registration
other_path(resource)
end
end
new registration form:
<form action="index.html">
<%= form_for(resource, as: resource_name, url: registration_path(resource_name)) do |f| %>
<%= devise_error_messages! %>
<div class="form-group">
<%= f.email_field :email, autofocus: true, placeholder: "Email", class: "form-control rounded input-lg text-center no-border" %>
</div>
<div class="form-group">
<% if #minimum_password_length %>
<em>(<%= #minimum_password_length %> characters minimum)</em>
<% end %><br />
<%= f.password_field :password, autocomplete: "off", placeholder: "Password", class: "form-control rounded input-lg text-center no-border" %>
</div>
<div class="form-group">
<%= f.password_field :password_confirmation, autocomplete: "off", placeholder: "Confirm Password", class: "form-control rounded input-lg text-center no-border" %>
</div>
<div class="checkbox i-checks m-b">
<label class="m-l">
<input type="checkbox" checked=""><i></i> Agree the terms and policy
</label>
</div>
<button type="submit" class="btn btn-lg btn-warning lt b-white b-2x btn-block btn-rounded"><i class="icon-arrow-right pull-right"></i><span class="m-r-n-lg">Sign up</span></button>
<% end %>
<div class="text-center m-t m-b"><small><%= link_to "Already have an account?", new_session_path(resource_name) %></small></div>
console:
Started GET "/users/index.html?utf8=%E2%9C%93&authenticity_token=KlAk4ctYpw%2F2eHGqZ0OsAymf5BxUPxeBiFzeOatn2JDUQJdPk8fGoB%2BmuN4oeN3KviQdVwN%2FxMfnjH4zIVooOg%3D%3D&user%5Bemail%5D=asdf%40asdf.com&user
%5Bpassword%5D=[FILTERED]&user%5Bpassword_confirmation%5D=[FILTERED]" for ::1 at 2016-10-25 22:10:37 -0400
Processing by UsersController#show as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"KlAk4ctYpw/2eHGqZ0OsAymf5BxUPxeBiFzeOatn2JDUQJdPk8fGoB+muN4oeN3KviQdVwN/xMfnjH4zIVooOg==", "user"=>{"email"=>"asdf#asdf.com", "password"=>"[FILTERED]
", "password_confirmation"=>"[FILTERED]"}, "id"=>"index"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 0], ["LIMIT", 1]]
Completed 404 Not Found in 3ms (ActiveRecord: 0.3ms)
ActiveRecord::RecordNotFound (Couldn't find User with 'id'=index):
app/controllers/users_controller.rb:6:in `show'
Rendering /Users/Joe/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout
Rendering /Users/Joe/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb
Rendered /Users/Joe/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_source.html.erb (3.7ms)
Rendering /Users/Joe/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb
Rendered /Users/Joe/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (1.8ms)
Rendering /Users/Joe/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb
Rendered /Users/Joe/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (2.0ms)
Rendered /Users/Joe/.rbenv/versions/2.3.0/lib/ruby/gems/2.3.0/gems/actionpack-5.0.0.1/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (69.3ms)
request params:
{"utf8"=>"✓",
"authenticity_token"=>"KlAk4ctYpw/2eHGqZ0OsAymf5BxUPxeBiFzeOatn2JDUQJdPk8fGoB+muN4oeN3KviQdVwN/xMfnjH4zIVooOg==",
"user"=>{"email"=>"asdf#asdf.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"},
"id"=>"index",
"format"=>"html"}

If you want to go to users#show, the correct path helper should be user_path(resource), is it what you want?

It looks like the issue is two-fold. The registrations controller is looking for the incorrect path but it also needs a proper id. I think the solution here is to pass it user_path(#user.id) instead of having resource as an argument where you have it in new_user_path(resource).
It's attempting to query for a User that has an ID of "Index" which doesn't exist and therefore it's throwing an error. You'll want to find the id of your new user and insert that to the route so that it finds that specific User profile. I used #user as an example. You can define that variable in the code or work with whatever variable you wish. I hope that helps!

Related

Rails - Not Redirecting even though it says “Redirected to http://localhost:3000” in my sever

I have a form_with that works in my server but not in my brother:
My form in my view :
<%= form_with url: sessions_path, method: "post" do |f|%>
<h3 class="text-center text-info">Se Connecter</h3>
<div class="form-group">
<%= label_tag "email", "Adresse mail:", class: "text-info" %><br>
<%= f.email_field "email", class: "form-control" %>
</div>
<div class="form-group">
<%= label_tag "password", "Mot De Passe", class: "text-info" %><br>
<%= f.password_field "password", class: "form-control" %>
</div>
<div class="form-group" style="padding: 20px;">
<%= f.submit "Se connecter", class: "btn btn-info btn-md" %>
</div>
<% end %>
My controller :
def create
user = User.find_by(email: params[:email])
if user && user.authenticate(params[:password])
session[:user_id] = user.id
redirect_to gossips_path, :notice => "Bienvenue <%= User.find_by(id: session[:user_id]).first_name %>"
else
flash.now[:danger] = 'Email ou Mot De Passe invalide'
render 'new'
end
end
My server :
Started POST "/sessions" for ::1 at 2020-10-04 13:10:25 +0200
Processing by SessionsController#create as JS
Parameters: {...}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."email" = $1 LIMIT $2 [["email", "..."], ["LIMIT", 1]]
↳ app/controllers/sessions_controller.rb:8
#<User:0x00007f667d7f36f0>
Redirected to http://localhost:3000/gossips
Completed 302 Found in 246ms (ActiveRecord: 0.2ms)
Started GET "/gossips" for ::1 at 2020-10-04 13:10:26 +0200
Processing by GossipsController#index as JS
Rendering gossips/index.html.erb within layouts/application
Gossip Load (0.4ms) SELECT "gossips".* FROM "gossips"
↳...
Rendered gossips/index.html.erb within layouts/application (75.5ms)
Completed 200 OK in 102ms (Views: 85.6ms | ActiveRecord: 12.8ms)
But my browser stay in the same page. I don't know why.
Can you help me?
<%= form_with url: sessions_path, method: "post", local: true do |f|%>
# ...
<% end %>
form_with unlike form_for defaults to remote: true. That means that the form will by default send an AJAX request and thus the redirect does nothing in the browser. You can see that its an AJAX request by:
Processing by SessionsController#create as JS

Unknown parameter in Rails 5.1 strong parameters issue

So my reconciliation model looks like this:
class Reconciliation < ApplicationRecord
belongs_to :location
belongs_to :company
has_and_belongs_to_many :inventory_items
accepts_nested_attributes_for :inventory_items, allow_destroy: true
end
My InventoryItem model looks like this:
class InventoryItem < ApplicationRecord
belongs_to :product
belongs_to :location, inverse_of: :inventory_items
has_and_belongs_to_many :reconciliations
end
In my ReconciliationsController, this is what my reconciliation_params looks like:
def new
#location = Location.find(params[:location_id])
#reconciliation = #location.reconciliations.new
#inventory_items = #location.inventory_items
#start_index = 0
#next_index = #start_index + 1
end
def reconciliation_params
params.require(:reconciliation).permit(:inventory_item_id, :location_id, :display_id, :inventory_items,
inventory_items_attributes: [:id, :quantity_left, :quantity_delivered, :_destroy]
)
end
This is the relevant section of my routes.rb:
resources :locations, shallow: true do
resources :inventory_items
resources :reconciliations
end
This is my views/reconciliations/_form.html.erb:
<%= simple_form_for #reconciliation, url: :location_reconciliations do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :location_id, as: :hidden %>
<%= f.simple_fields_for :inventory_item do |inventory| %>
<%= inventory.input :quantity_left %>
<%= inventory.input :quantity_delivered %>
<% end %>
</div>
<div class="form-actions">
<%= f.button :submit, "Update", class: "btn btn-primary" %>
</div>
<% end %>
This is my app/views/reconciliations/new.html.erb:
<% if params[:next].nil? %>
<%= render 'form', reconciliation: #reconciliation, inventory_item: #inventory_items[#start_index] %>
<% else %>
<%= render 'form', reconciliation: #reconciliation, inventory_item: #inventory_items[#next_index] %>
<% end %>
This is my log when I try to create a reconciliation object:
Started POST "/locations/2/reconciliations" for 127.0.0.1 at 2018-03-24 23:16:33 -0500
Processing by ReconciliationsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"JZvhwloo0+XM9bmptxXGfnDw==", "reconciliation"=>{"location_id"=>"2", "inventory_item"=>{"quantity_left"=>"1", "quantity_delivered"=>"170"}}, "commit"=>"Update", "location_id"=>"2"}
Unpermitted parameter: :inventory_item
Location Load (0.9ms) SELECT "locations".* FROM "locations" WHERE "locations"."id" = $1 LIMIT $2 [["id", 2], ["LIMIT", 1]]
(0.6ms) BEGIN
(0.7ms) ROLLBACK
Rendering reconciliations/new.html.erb within layouts/application
InventoryItem Load (1.0ms) SELECT "inventory_items".* FROM "inventory_items" WHERE "inventory_items"."location_id" = $1 [["location_id", 2]]
Product Load (1.0ms) SELECT "products".* FROM "products" WHERE "products"."id" = $1 LIMIT $2 [["id", 2], ["LIMIT", 1]]
Rendered reconciliations/_form.html.erb (45.9ms)
Rendered reconciliations/new.html.erb within layouts/application (66.8ms)
Rendered shared/_navbar.html.erb (1.3ms)
Completed 200 OK in 202ms (Views: 115.1ms | ActiveRecord: 29.1ms)
I have tried simply adding :inventory_item to my params.require(:reconciliation).permit(..), but that doesn't work.
What am I missing?
Edit 1
When I checked the HTML for the inputs on my form, within the simple_fields_for, the HTML seems to be fine:
<input class="string required" type="text" name="reconciliation[inventory_item][quantity_left]" id="reconciliation_inventory_item_quantity_left">
Edit 2
When I change the simple_fields_for call to be plural, i.e. :inventory_items, rather than :inventory_item like this:
That entire portion of the form disappears altogether.
This is what the HTML looks like:
<div class="form-inputs">
<div class="input hidden reconciliation_location_id"><input class="hidden" type="hidden" value="2" name="reconciliation[location_id]" id="reconciliation_location_id"></div>
</div>
This is how the HTML looks when that simple_field_for :inventory_item is singular:
<div class="form-inputs">
<div class="input hidden reconciliation_location_id"><input class="hidden" type="hidden" value="2" name="reconciliation[location_id]" id="reconciliation_location_id"></div>
<div class="input string required reconciliation_inventory_item_quantity_left"><label class="string required" for="reconciliation_inventory_item_quantity_left"><abbr title="required">*</abbr> Quantity left</label><input class="string required" type="text" name="reconciliation[inventory_item][quantity_left]" id="reconciliation_inventory_item_quantity_left"></div>
<div class="input string required reconciliation_inventory_item_quantity_delivered"><label class="string required" for="reconciliation_inventory_item_quantity_delivered"><abbr title="required">*</abbr> Quantity delivered</label><input class="string required" type="text" name="reconciliation[inventory_item][quantity_delivered]" id="reconciliation_inventory_item_quantity_delivered"></div>
</div>
I have tried simply adding :inventory_item to my params.require(:reconciliation).permit(..), but that doesn't work.
If you want permit inventory_item, you must specify its structure, because it is not a simple field, but a hash:
def reconciliation_params
params.require(:reconciliation).permit(:location_id, :display_id, inventory_item: [:id, :quantity_left, :quantity_delivered] )
end
By looking at your log, you are not passing the inventory_item_id, which might be needed to update this specific item:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"JZvhwloo0+XM9bmptxXGfnDw==",
"reconciliation"=>{"location_id"=>"2", "inventory_item"=>
{"quantity_left"=>"1", "quantity_delivered"=>"170"}},
"commit"=>"Update", "location_id"=>"2"}
You could add it as a hidden field in the nested form.
Form of association should be plural f.simple_fields_for :inventory_items.
You should initialize a new inventory_item object in the new controller's action
def new
#reconciliation = Reconciliation.new
# you can create as many new items as you want
#reconciliation.inventory_items.build
end
If you want to dynamically add items to the form i advise you to use https://github.com/nathanvda/cocoon
BUT it looks like you want to add existing inventory_item to a new reconciliation, you better use has_many through assocations http://guides.rubyonrails.org/association_basics.html#choosing-between-has-many-through-and-has-and-belongs-to-many
Its easier to add a join model objects with neccessary fields and associations.
Another advise: do not send local variable to partial if you are using instance variable in this partial
# render partial
render 'form', reconciliation: #reconciliation
# partial with form for local variable
simple_form_for reconciliation
and i think your form partial will not work for the edit action because of hardcoded url, you can pass url in a variable:
# new html
render 'form', reconciliation: #reconciliation, url_var: location_reconciliations(#location)
# edit
render 'form', reconciliation: #reconciliation, url_var: reconciliations(#reconciliation)
# form
simple_form_for reconciliation, url: url_var

rails form_tag doesn't work anymore

Surprisingly i can't make this simple form_tag to send me the params.. for an hour.. It worked on my last project. I did a copy of it, used different Ruby version and now it doesn't work. Tried many things but it just don't work.
I have this block:
<div class="row">
<div class="col-md-8">
<div id="light-pagination" class="pagination"></div>
</div>
<div class="col-md-4" style='float:right'>
<%= form_tag("/go_to_show_question", class: "form-inline", method: "get") do %>
<%= hidden_field_tag(:id, #question_group.id) %>
<%= search_field_tag :question, '', size: 5, class: 'form-control' %>
<%= submit_tag r("tests.go_to_question"), class: 'btn btn-default' %>
<% end %>
</div>
</div><br>
I am inputting a number and clicking on 'Go to question'. And it sends only:
{"controller"=>"question_groups", "action"=>"go_to_show_question", "locale"=>"en"}
Where is 'id' and 'question'? why they are not sent together?
I believe this is something stupid but i cant find what.. It worked before. I didnt change it i believe.
This is the generated HTML
<div class="row">
<div class="col-md-8">
<div id="light-pagination" class="pagination"></div>
</div>
<div class="col-md-4" style='float:right'>
<form class="form-inline" action="/go_to_show_question" accept-charset="UTF-8" method="get"><input name="utf8" type="hidden" value="✓" />
<input type="hidden" name="id" id="id" value="28" />
<input type="search" name="question" id="question" value="" size="5" class="form-control" />
<input type="submit" name="commit" value="Go to question" class="btn btn-default" />
</form>
</div>
</div><br>
Routes:
Rails.application.routes.draw do
... other routes ...
scope ":locale", locale: /#{I18n.config.available_locales.join("|")}/ do
... other routes ...
get 'go_to_show_question' => 'question_groups#go_to_show_question'
... other routes ...
end
get '*path', to: redirect("/#{(I18n.locale)}/%{path}"), constraints: lambda { |req| !req.path.starts_with? "/#{I18n.locale}/" }
match '', to: redirect("/#{(I18n.locale)}"), via: [:get, :post, :put, :delete]
end
Controller:
class QuestionGroupsController < ApplicationController
def go_to_show_question
redirect_to show_question_group_path(:id => params[:id], :question => (params[:question].to_i - 1))
end
end
This request reaches my controller. but without id, question params.
And this is the Log
Processing by QuestionGroupsController#go_to_show_question as HTML
Parameters: {"locale"=>"en"}
User Load (0.2ms) SELECT `users`.* FROM `users` WHERE `users`.`id` = 1 ORDER BY `users`.`id` ASC LIMIT 1
{"controller"=>"question_groups", "action"=>"go_to_show_question", "locale"=>"en"}
Redirected to http://localhost:3000/en/show_question_group?question=-1
Completed 302 Found in 2ms (ActiveRecord: 0.2ms)
Found the answer:
<%= form_tag("/en/go_to_show_question", class: "form-inline", method: "get") do %>
<%= hidden_field_tag(:id, #question_group.id) %>
<%= search_field_tag :question, '', size: 5, class: 'form-control' %>
<%= submit_tag r("tests.go_to_question"), class: 'btn btn-default' %>
<% end %>
I just didnt add the locale in front of my URL of form.
Even trough my route worked fine, but the :locale scope parsed the request and deleted my params.
It was like
Started GET "/go_to_show_question?utf8=%E2%9C%93&id=28&question=88&commit=Go+to+question" for 127.0.0.1 at 2017-01-07 16:41:08 +0100
parsed into
Started GET "/en/go_to_show_question" for 127.0.0.1 at 2017-01-07 16:41:08 +0100
Processing by QuestionGroupsController#go_to_show_question as HTML
Parameters: {"locale"=>"en"}

New ticket is being created when loading a new form

This is my first question on here, so I am hoping I have not asked it incorrectly.
I have a generic new action on my tickets controller. Whenever I load tickets/new, it is creating a new item in the DB and committing it.
Here is the output from the server when the page is loading.
Started GET "/tickets/new" for ::1 at 2016-02-10 21:14:47 -0800
Processing by TicketsController#new as HTML
Customer Load (0.4ms) SELECT `customers`.* FROM `customers` WHERE `customers`.`email` = 'tim#tim.com' LIMIT 1
(0.3ms) BEGIN
SQL (0.5ms) INSERT INTO `tickets` (`category`, `created_at`, `updated_at`) VALUES (3, '2016-02-11 05:14:47', '2016-02-11 05:14:47')
(6.4ms) COMMIT
Rendered tickets/_new_form.html.erb (23.3ms)
Rendered tickets/new.html.erb within layouts/application (48.4ms)
Rendered layouts/_user_nav.html.erb (0.8ms)
Rendered layouts/_navbar.html.erb (0.5ms)
Rendered layouts/_flashes.html.erb (0.5ms)
Rendered layouts/_minimal.html.erb (759.5ms)
Completed 200 OK in 893ms (Views: 822.1ms | ActiveRecord: 21.3ms)
This is the from the tickets controller.
def new
#ticket = Ticket.new
end
Here is the code for the form.
<%= form_for(#ticket, html: { class: 'form-horizontal' }) do |f| %>
<%= f.error_notification %>
<%= f.hidden_field(:category) %>
<%= f.hidden_field(:severity) %>
<br>
<%= f.form_group :summary do |f| %>
<%= f.label :summary, class: 'control-label col-md-2' %>
<div class='col-md-8'>
<%= f.text_field :summary, class: 'form-control' %>
<%= f.error_messages %>
</div>
<% end %>
<%= f.form_group :detail do |f| %>
<%= f.label :detail, class: 'control-label col-md-2' %>
<div class='col-md-8'>
<%= f.text_area :detail, class: 'form-control' %>
<%= f.error_messages %>
</div>
<% end %>
<br>
</div>
<div class="form-actions col-md-offset-2 col-md-10">
<%= f.submit 'Create', class: 'btn btn-primary' %>
<%= link_to "Cancel", tickets_path, class: 'btn' %>
</div>
<% end %>
Here are the relevant routes.
resources :tickets do
collection do
get :step_1
get :new_ticket
get :billing_new_1
get :internet_step_1
get :internet_step_2
get :internet_modem_reset
get :internet_step_1
get :internet_step_2
get :internet_create_1
get :internet_create_2
get :tv_step_1
get :tv_step_2
get :tv_step_3
get :tv_create_1
get :tv_create_2
get :tv_create_3
get :closed
get :sidenav
end
member do
put :close
end
resources :notes
resources :appointments
end
Help!!
--Tim
INSERT INTO `tickets` (`category`, `created_at`, `updated_at`) VALUES (3, '2016-02-11 05:14:47', '2016-02-11 05:14:47')
This is getting category (3) from somewhere, suggesting that there is some functionality somewhere which is saving the #ticket.
The simplest explanation I can see is that you have a before_action somewhere. It would benefit to show your entire TicketsController:
#app/controllers/tickets_controller.rb
class TicketsController < ApplicationController
before_action :set_user #-> something like this??
end
Since you're new, you can make your routes much more succinct (multiple resources):
#config/routes.rb
methods = %i(step_1 new_ticket billing_new_1 internet_step_1 internet_step_2 internet_modem_reset internet_create_1 internet_create_2 tv_step_1 tv_step_2 tv_step_3 tv_create_1 tv_create_2 tv_create_3 closed sidenav)
resources :tickets do
resources :notes, :appointments
collection do
methods.each {|method| get method }
end
put :close, on: :member
end
I ended up starting the whole ticket class over.
I think the error was in my html.
My guess is that the if statement with the bang was causing the ticket to save, because of an enum with that name on the model.
Here is what I think was the bad html.
<% if #ticket.category == :tv %>
Ok. Your tv is down, but your internet is still working.
<br>
Do you have any more details to add? If so, add them here. If not, just hit sumbit and we will open up a ticket with all of the information that you have provided us.
<% elsif #ticket.internet! %>
Ok. Your internet is down, but your tv is still working.
<br>
Do you have any more details to add? If so, add them here. If not, just hit sumbit and we will open up a ticket with all of the information that you have provided us.
<% elsif #ticket.billing %>
I am fresh out of questions.
<br>
Do you have any more details to add? If so, add them here. If not, just hit sumbit and we will open up a ticket with all of the information that you have provided us.
<% elsif #ticket.category == :internet_and_tv %>
Ok. Your cable and internet are both down.'%>
<br>
Do you have any more details to add? If so, add them here. If not, just hit sumbit and we will open up a ticket with all of the information that you have provided us.'%>
<% else #ticket.category == :plant %>
<%end%>

form_for with validation does not called "create" action correctly

I had a form that I want user to answer every question, so I add a model-level validation.
I supposed if it pass validation, it should redirect to another page call "scenario" (I haven't finish it's view so it should show template missing). If it does not pass validation, it should render once again to the new page, remains the information already filled in, and show validation error.
But no matter I filled out those fields or not, when I click submit button, it always show me the index page instead of "new" or "scenario"(which should be template missing). It seems ignore what I have wrote in the action "create", and "create" is never been called.
I use rails c and insert a new record to test validation. It does work well, so I guess there is no problem for my model and validation.
I also try to make form_for redirect to "scenario" directly, to make sure it work well for form_for, and it does show templete missing to me, so there might be some problem for "create" itself. I really don't know what's going wrong.
<%= form_for #subject, :url => { :controller => 'appstores', :action => 'scenario' } do |f| %>
There is a similar question: rails form_for never invokes the create controller action to use redirect_to.
I had try to use "respond_with", not work. And also check my controller is named as appstroes_controller.rb with resources :appstores in routes.rb.
I use rails 4.2.4, ruby 2.0.0, and bootstrap 3, don't know whether the version cause those problem or not.
Any help would be appreciated, thanks!
app/controller/appstores_controller.rb
class AppstoresController < ApplicationController
def index
end
def new
#subject = Subjectinfo.new
end
def create
#subject = Subjectinfo.new(params[:subjectinfo])
if #subject.save
redirect_to :action => "scenario"
else # if not pass DB validation
render :action => :new
end
end
def scenario
end
end
app/view/appstores/new.html.erb
<%= form_for #subject, :url => { :controller => 'appstores', :action => 'create' } do |f| %>
<form class="form-horizontal">
<div class="form-group">
<%= f.label :username, "User Name:", :class=>"control-label", :for=>"username" %>
<% if #subject.errors[:username].presence %>
<span class="model-error"><%= #subject.errors[:username].join(", ") %></span>
<% end %>
<%= f.text_field :username, :autocomplete=>"off", :placeholder=>"User Name", :class=>"form-control", :id=>"username" %>
</div>
<div class="form-group">
<%= f.label :mobile_user, "Are you a mobile device user?", :class=>"control-label", :for=>"mobile_user" %>
<% if #subject.errors[:mobile_user].presence %>
<span class="model-error"><%= #subject.errors[:mobile_user].join(", ") %></span>
<% end %>
<div class="radio radio-primary">
<%= f.radio_button :mobile_user, "1", :id=>"mobile_user_1" %>
<%= f.label :mobile_user, "Yes", :class=>"control-label", :for=>"mobile_user_1" %>
</div>
<div class="radio radio-primary">
<%= f.radio_button :mobile_user, "0", :id=>"mobile_user_0" %>
<%= f.label :mobile_user, "No", :class=>"control-label", :for=>"mobile_user_0" %>
</div>
</div>
<div class="text-center">
<%= f.submit "NEXT", :class => "btn btn-default btn-outline btn-lg" %>
</div>
</form>
<% end %>
app/modle/subjectinfo.rb
(to support "attr_accessible" for rails 4, I had put "gem 'protected_attributes'" in my Gemfile)
class Subjectinfo < ActiveRecord::Base
validates_presence_of :username, :mobile_user
attr_accessible :username, :mobile_user
end
config/routes.rb
AppStore::Application.routes.draw do
match ':controller(/:action(/:id(.:format)))', :via => :all
root :to => "appstores#index"
resources :appstores
get "appstores/scenario"=>"appstores#scenario"
end
rake routes
Prefix Verb URI Pattern Controller#Action
/:controller(/:action(/:id(.:format))) :controller#:action
root GET / appstores#index
appstores GET /appstores(.:format) appstores#index
POST /appstores(.:format) appstores#create
new_appstore GET /appstores/new(.:format) appstores#new
edit_appstore GET /appstores/:id/edit(.:format) appstores#edit
appstore GET /appstores/:id(.:format) appstores#show
PATCH /appstores/:id(.:format) appstores#update
PUT /appstores/:id(.:format) appstores#update
DELETE /appstores/:id(.:format) appstores#destroy
appstores_rfscenario GET /appstores/rfscenario(.:format) appstores#rfscenario
Btw, here is what I saw form terminal, this is when I filled in all the fields.
Started POST "/appstores" for 127.0.0.1 at 2015-11-03 22:25:54 +0800
Processing by AppstoresController#index as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"7WV4Iw/0uHNSnuXpr8qa39oFEF9gZfKm8EyHGQna0o0=", "subjectinfo"=>{"username"=>"a1", "mobile_user"=>"1"}, "commit"=>"NEXT"}
Rendered appstores/index.html.erb within layouts/application (12.6ms)
Completed 200 OK in 91ms (Views: 88.0ms | ActiveRecord: 0.0ms)
Here is when I leave them blank, but no matter it is blank or not, it always render to index......
Started POST "/appstores" for 127.0.0.1 at 2015-11-03 22:25:54 +0800
Processing by AppstoresController#index as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"7WV4Iw/0uHNSnfuXpr8qa39oFEF9gZfKm8EyHGQna0o0=", "subjectinfo"=>{"esearch"=>""}, "commit"=>"NEXT"}
Rendered appstores/index.html.erb within layouts/application (12.6ms)
Completed 200 OK in 91ms (Views: 88.0ms | ActiveRecord: 0.0ms)
Remove the line match ':controller(/:action(/:id(.:format)))', :via => :all from your routes.rb file and never use it anymore. This pattern matches any route and it is on the first position, other routes in your file don't have a chance at all because of that.

Resources