I am sending an AJAX request from my frontend to rails for a patch request but getting an action cannot be found error.
So far, I have double checked my routes and controller to make sure there were no mistakes. My create action is working fine which is in the users controller. Ive also double checked my AJAX request to make sure it is going to the correct url. My AJAX request is also for an AWS upload if that helps.
Here are my routes
namespace :api, defaults: {format: :json} do
resources :users, only: [:create, :update, :show]
resource :session, only: [:create, :destroy, :show]
end
root "static_pages#root"
end
here is my controller with the update action
class Api::UsersController < ApplicationController
def create
#user = User.new(user_params)
if #user.save
login(#user)
render "api/users/show"
else
render json: #user.errors.full_messages, status: 422
end
def show
#user = User.find(params[:id])
render "api/users/show"
end
def update
#user = User.find(params[:id])
if #user.update_attributes(user_params)
render "api/users/show"
else
render json: #user.errors.full_messages
end
end
end
def user_params
params.require(:user).permit(:email, :password, :first_name, :last_name, :DOB, :gender, :prof_photo, :cover_photo)
end
end
Update: ajax request for AWS user photo upload.
export const updateUser = (userId, formData) => {
return $.ajax({
method: "PATCH",
url: `api/users/${userId}`,
data: formData,
contentType: false,
processData: false
})
}
Finally here are the server logs
AbstractController::ActionNotFound - The action 'update' could not be found for Api::UsersController:
Started GET "/" for ::1 at 2019-10-06 07:49:03 -0400
Processing by StaticPagesController#root as HTML
Rendering static_pages/root.html.erb within layouts/application
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."session_token" = $1 LIMIT $2 [["session_token", "mRbshUiTIXjVd3LpZSiWvA"], ["LIMIT", 1]]
↳ app/controllers/application_controller.rb:10
ActiveStorage::Attachment Load (0.7ms) SELECT "active_storage_attachments".* FROM "active_storage_attachments" WHERE "active_storage_attachments"."record_id" = $1 AND "active_storage_attachments"."record_type" = $2 AND "active_storage_attachments"."name" = $3 LIMIT $4 [["record_id", 2], ["record_type", "User"], ["name", "prof_photo"], ["LIMIT", 1]]
↳ app/views/api/users/_user.json.jbuilder:3
ActiveStorage::Blob Load (1.1ms) SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = $1 LIMIT $2 [["id", 2], ["LIMIT", 1]]
↳ app/views/api/users/_user.json.jbuilder:3
Rendered api/users/_user.json.jbuilder (7.2ms)
Rendered static_pages/root.html.erb within layouts/application (13.8ms)
Completed 200 OK in 93ms (Views: 86.5ms | ActiveRecord: 2.8ms)
Started PATCH "/api/users/2" for ::1 at 2019-10-06 07:55:37 -0400
AbstractController::ActionNotFound - The action 'update' could not be found for Api::UsersController:````
Found the rookie mistake! The end statement for create action was all the way at the bottom (hence only my create action was working) Make sure to check your end statements!
Related
The "destroy" method is not working on my site. I created a "delete" link, but when I click it I just get redirected.
Here is the controller with the destroy method:
class PostsController < ApplicationController
def index
#posts = Post.all
end
def show
#post = Post.find(params[:id])
end
def new
#post = Post.new
end
def create
#post = Post.new(post_params)
if #post.save
redirect_to #post
else
render :new, status: :unprocessable_entity
end
end
def edit
#post = Post.find(params[:id])
end
def update
#post = Post.find(params[:id])
if #post.update(post_params)
redirect_to #post
else
render :edit, status: :unprocessable_entity
end
end
def destroy
#post = Post.find(params[:id])
#post.destroy
redirect_to root_path, status: :see_other
end
private
def post_params
params.require(:post).permit(:title, :description, :image, :price)
end
end
Nothing fancy. And here is the link in my posts/show.html.erb view:
<%= link_to 'Delete', root_path,
method: :delete,
data: { confirm: 'Are you sure?' } %>
Doesn't work - I just get redirected to the root path, and the post I tried to delete remains.
I tried removing a post in the rails console, and that did work.
Rails 7.0.4
Ruby 3.1.2
Server output after clicking "delete" link on local site:
Started GET "/posts/3" for ::1 at 2022-10-09 23:59:02 -0400
ActiveRecord::SchemaMigration Pluck (0.2ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
Processing by PostsController#show as HTML
Parameters: {"id"=>"3"}
Post Load (0.1ms) SELECT "posts".* FROM "posts" WHERE "posts"."id" = ? LIMIT ? [["id", 3], ["LIMIT", 1]]
↳ app/controllers/posts_controller.rb:7:in `show'
Rendering layout layouts/application.html.erb
Rendering posts/show.html.erb within layouts/application
ActiveStorage::Attachment Load (0.1ms) SELECT "active_storage_attachments".* FROM "active_storage_attachments" WHERE "active_storage_attachments"."record_id" = ? AND "active_storage_attachments"."record_type" = ? AND "active_storage_attachments"."name" = ? LIMIT ? [["record_id", 3], ["record_type", "Post"], ["name", "image"], ["LIMIT", 1]]
↳ app/views/posts/show.html.erb:11
ActiveStorage::Blob Load (0.1ms) SELECT "active_storage_blobs".* FROM "active_storage_blobs" WHERE "active_storage_blobs"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
↳ app/views/posts/show.html.erb:12
Comment Load (0.1ms) SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = ? [["post_id", 3]]
↳ app/views/posts/show.html.erb:23
Rendered collection of templates [0 times] (Duration: 0.0ms | Allocations: 35)
Rendered comments/_form.html.erb (Duration: 31.1ms | Allocations: 6334)
Rendered posts/show.html.erb within layouts/application (Duration: 142.9ms | Allocations: 31474)
Rendered layout layouts/application.html.erb (Duration: 300.1ms | Allocations: 53293)
Completed 200 OK in 402ms (Views: 312.5ms | ActiveRecord: 2.1ms | Allocations: 66385)
Started GET "/rails/active_storage/disk/eyJfcmFpbHMiOnsibWVzc2FnZSI6IkJBaDdDVG9JYTJWNVNTSWhiR28xZVRKamJucHhZM0pxZFhaak9YZGxZelY0ZVdwbGREWnlNZ1k2QmtWVU9oQmthWE53YjNOcGRHbHZia2tpWldsdWJHbHVaVHNnWm1sc1pXNWhiV1U5SW1sc1h6RTFPRGg0VGk0ek1qSTNNRGc0TlRZMVh6SmlkWGd1Y0c1bklqc2dabWxzWlc1aGJXVXFQVlZVUmkwNEp5ZHBiRjh4TlRnNGVFNHVNekl5TnpBNE9EVTJOVjh5WW5WNExuQnVad1k3QmxRNkVXTnZiblJsYm5SZmRIbHdaVWtpRG1sdFlXZGxMM0J1WndZN0JsUTZFWE5sY25acFkyVmZibUZ0WlRvS2JHOWpZV3c9IiwiZXhwIjoiMjAyMi0xMC0xMFQwNDowMTo0My45NDVaIiwicHVyIjoiYmxvYl9rZXkifX0=--00b620d927983a0cba2300d10b1e2234b9306a84/il_1588xN.3227088565_2bux.png" for ::1 at 2022-10-09 23:59:03 -0400
Processing by ActiveStorage::DiskController#show as PNG
Parameters: {"encoded_key"=>"[FILTERED]", "filename"=>"il_1588xN.3227088565_2bux"}
Completed 304 Not Modified in 7ms (ActiveRecord: 0.0ms | Allocations: 559)
Looks like you have an issue with Turbo or Rails UJS.
These should really work and send a DELETE request via javascript:
# Turbo
link_to "delete", #post, data: { turbo_method: :delete }
# Rails UJS
link_to "delete", #post, method: :delete
If your javascript is broken than data and method attributes are ignored and you're just clicking a link to show #post, which is what's happening in the log.
On the other hand:
data-turbo-method changes the link request type from the default GET.
Ideally, non-GET requests should be triggered with forms, but
data-turbo-method might be useful where a form is not possible.
https://turbo.hotwired.dev/reference/attributes
To trigger a DELETE request with a form you can use button_to, which creates a little form and rails correctly handles routing to destroy action:
button_to "Delete", #post, method: :delete
https://api.rubyonrails.org/classes/ActionView/Helpers/UrlHelper.html#method-i-button_to
Here is the code I'm trying to use in my controller:
profiles_controller.rb:
class ProfilesController < ApplicationController
...
def update
respond_to do |format|
# assume valid data sent (I've already tested for this)
if #user.update(user_params)
# password_reset? check's parameter passed to action that a check box was
# checked (which enables/disables password/confirmation fields. If unchecked,
# fields are disabled and no password parameters are sent to this action.
# #user was set to current_user in a before_action already
# inspecting #user at this point returns the same thing as current_user here
sign_in(:user, #user) if password_reset?
# current_user is still set to #user and is valid
# after redirection current_user becomes nil
format.html {
redirect_to home_path, notice: 'Your profile was successfully updated.'
}
else
format.html { render :edit }
end
end
end
...
private
# Never trust parameters from the scary internet, only allow the white list through.
def user_params
#user_params ||= params.require(:user).permit(:first_name, :last_name, :email, :phone, :password, :password_confirmation, :reset_password)
end
def password_reset?
#user_params["reset_password"] == "1"
end
end
application_controller.rb:
class ApplicationController < ActionController::Base
...
private
...
def require_user
logger.debug "IN REQUIRE_USER, CURRENT_USER IS: #{current_user.inspect}"
unless current_user
store_location
redirect_to new_user_session_url, notice: "That url doesn't exist."
return false
end
end
def require_admin
# this line will actually log a user in
#sign_in(:user, User.first) unless current_user
logger.debug "IN REQUIRE_ADMIN, CURRENT_USER IS: #{current_user.inspect}"
unless current_user && current_user.is_admin?
redirect_to(home_path, notice: "That url doesn't exist.") and return false
end
end
...
end
development.log:
Started PATCH "/profile" for 127.0.0.1 at 2019-05-28 10:38:45 -0700
Processing by ProfilesController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"....", "user"=>{....}, "commit"=>"Update Profile"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 1], ["LIMIT", 1]]
↳ app/controllers/application_controller.rb:47
IN REQUIRE_USER, CURRENT_USER IS: #<User id: 1 ....>
(0.1ms) begin transaction
↳ app/controllers/profiles_controller.rb:16
User Exists (0.4ms) SELECT 1 AS one FROM "users" WHERE LOWER("users"."email") = LOWER(?) AND "users"."id" != ? LIMIT ? [["email", "...."], ["id", 1], ["LIMIT", 1]]
↳ app/controllers/profiles_controller.rb:16
User Update (0.3ms) UPDATE "users" SET "encrypted_password" = ?, "updated_at" = ? WHERE "users"."id" = ? [["encrypted_password", "$2a$11...."], ["updated_at", "2019-05-28 17:38:45.346414"], ["id", 1]]
↳ app/controllers/profiles_controller.rb:16
(2.3ms) commit transaction
↳ app/controllers/profiles_controller.rb:16
PASSWORDS PASSED IN SO USER PASSWORD CHANGE OCCURRED
REDIRECTING TO HOME PATH
Redirected to http://localhost:3000/admin
Completed 302 Found in 121ms (ActiveRecord: 3.2ms)
Started GET "/admin" for 127.0.0.1 at 2019-05-28 10:38:45 -0700
Processing by Admin::PagesController#index as HTML
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 1], ["LIMIT", 1]]
↳ app/controllers/application_controller.rb:65
IN REQUIRE_ADMIN, CURRENT_USER IS: nil
Redirected to http://localhost:3000/
Filter chain halted as :require_admin rendered or redirected
Completed 302 Found in 2ms (ActiveRecord: 0.2ms)
Started GET "/" for 127.0.0.1 at 2019-05-28 10:38:45 -0700
Processing by PagesController#index as HTML
Rendering pages/index.html.erb within layouts/application
Rendered pages/index.html.erb within layouts/application (0.7ms)
Rendered application/_navigation.html.erb (1.7ms)
Rendered application/_alert.html.erb (0.3ms)
Completed 200 OK in 1152ms (Views: 1151.2ms | ActiveRecord: 0.0ms)
I've searched around and seen by_pass: true being passed to sign_in but that doesn't help. I've also tried #current_user = #user once I've signed the user in (#current_user is the direct instance variable for the Devise controller btw) and that does not help either.
Any ideas?
Devise ignores signin if the user is already signed in, try:
if #user.saved_change_to_encrypted_password? # for rails 5+, for previous - .encrypted_password_changed?
sign_in #user, force: true
end
You can signin new session if the user is already signed in.
Devise said
# Sign in a user bypassing the warden callbacks and stores the user
# straight in session. This option is useful in cases the user is
# signed in, but we want to refresh the credentials in session.
Please use like below one.
bypass_sign_in(#user)
I am trying to re-create a stack overflow like app. One user asks a question, and others can answer. I have a nested form indented on the question's page to get answers from other users.
I am having a difficult time to retrieve the data after the answer is posted, and I have set #answer incorrectly on the questions controller page in the update action, and I can't figure out how to properly retrieve this variable given that the params coming through the questions_controller does not have details of the answer set separately. How do I retrieve the params part related to #answer so that I can set the variable, or maybe I need to use different routes for that?
My form looks like this:
<%= form_for #question do |form| %>
<%=form.fields_for :answer do |answer_form| %>
<div class="form-group">
<%=answer_form.text_area :answer_attributes, placeholder: "Add your answer", rows:10, class:"form-control" %>
<%=answer_form.hidden_field :user_id, value: current_user.id, class:'d-none' %>
<%=answer_form.hidden_field :question_id, value: #question.id %>
</div>
<% end %>
<div>
<%=form.submit 'Post Your Answer', class: 'btn-primary' %>
</div>
<% end %>
My Question model looks like this:
class Question < ApplicationRecord
has_many :answers, dependent: :destroy
belongs_to :user
accepts_nested_attributes_for :answers
validates :headline, presence: true , length: { minimum: 20 }
validates :body, presence: true, length: { minimum: 50 }
validates_associated :answers
end
and the Answer model is:
class Answer < ApplicationRecord
belongs_to :user
belongs_to :question
validates :body, presence: true, length: { minimum: 50 }
end
Questions controller:
class QuestionsController < ApplicationController
before_action :authenticate_user!, except: [:index, :show]
before_action :set_question, except: [:index, :new, :create]
def index
#questions = Question.all.order("id DESC")
end
def show
#question = Question.find(params[:id])
#user = User.find(#question.user_id)
#answers = #question.answers
#answer = Answer.new
end
def new
#question = Question.new
#question.answers.new
end
def create
#question = current_user.questions.new(question_params)
if #question.save
flash[:notice] = "You have successfully posted your question"
redirect_to #question
else
#errors = #question.errors.full_messages
render action: :new
end
end
def edit
set_question
#question = Question.find(params[:id])
end
def update
#question = Question.find(params[:id])
#question.update(question_params)
#answer = #question.answers.new(question_params)
#question.answers.first.user_id = current_user.id
if #question.save
flash[:notice] = "You have sucessfully posted your answer"
redirect_to #question
else
redirect_to new_question_answer_path(#answer), flash: { danger: #question.errors.full_messages.join(",")}
end
end
private
def set_question
#question = Question.find(params[:id])
end
def question_params
params.require(:question).permit(:headline, :body, :user_id, :answer, answers_attributes:[:body, :user_id, :question_id])
end
end
Answers controller:
class AnswersController < ApplicationController
before_action :find_question
def index
#answers = #question.answers
#user = User.find(#question.user_id)
end
def show
#answer = Answer.find(params[:id])
#user = User.find(#question.user_id)
end
def new
#answer = Answer.new(:question_id => #question.id)
end
def create
#answer = Answer.new(answer_params)
if #answer.save
flash[:notice] = "You have sucessfully created the answer."
redirect_to(answers_path(#answer, :question_id => #question.id))
else
flash[:alert] = "Failed to save the answer."
#errors = #answer.errors.full_messages
render :new
end
end
def edit
#answer = Answer.find(params[:id])
end
def update
#answer = Answer.find(params[:id])
if #answer.update_attributes(answer_params)
flash[:notice] = "You have sucessfully updated the answer."
redirect_to(answer_path(#answer, :question_id => #question.id))
else
render :edit
end
end
def delete
#answer = Asnwer.find(params[:id])
end
def destroy
#answer = Answer.find(params[:id])
#answer.destroy
flash[:notice] = "Answer was destroyed"
redirect_to(answers_path)
end
private
def answer_params
params.require(:answer).permit(:body, :user_id, :question_id)
end
def find_question
#question = Question.find(params[:question_id])
end
end
My routes file looks like this:
Rails.application.routes.draw do
get 'questions/index'
root to: 'questions#index'
resources :questions do
resources :answers
end
devise_for :users
# For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end
UPDATE: here are the logs from the moment the server was started and the index page displayed to the moment where I go to the questions page and log the answer
rails server
=> Booting Puma
=> Rails 5.2.2 application starting in development
=> Run `rails server -h` for more startup options
Puma starting in single mode...
* Version 3.12.0 (ruby 2.6.0-p0), codename: Llamas in Pajamas
* Min threads: 5, max threads: 5
* Environment: development
* Listening on tcp://0.0.0.0:3000
Use Ctrl-C to stop
Started GET "/questions/11/answers" for 127.0.0.1 at 2019-03-07 16:10:13 +0600
(1.4ms) SELECT "schema_migrations"."version" FROM "schema_migrations" ORDER BY "schema_migrations"."version" ASC
↳ /Users/irina/.rvm/gems/ruby-2.6.0/gems/activerecord-5.2.2/lib/active_record/log_subscriber.rb:98
Processing by AnswersController#index as HTML
Parameters: {"question_id"=>"11"}
Question Load (0.8ms) SELECT "questions".* FROM "questions" WHERE "questions"."id" = $1 LIMIT $2 [["id", 11], ["LIMIT", 1]]
↳ app/controllers/answers_controller.rb:65
User Load (2.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 3], ["LIMIT", 1]]
↳ app/controllers/answers_controller.rb:6
Rendering answers/index.html.erb within layouts/application
Answer Load (0.9ms) SELECT "answers".* FROM "answers" WHERE "answers"."question_id" = $1 [["question_id", 11]]
↳ app/views/answers/index.html.erb:11
User Load (1.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 3], ["LIMIT", 1]]
↳ app/views/answers/_new.html.erb:7
Rendered answers/_new.html.erb (61.7ms)
Rendered answers/index.html.erb within layouts/application (92.7ms)
[Webpacker] Compiling…
Started GET "/questions/11/answers" for 127.0.0.1 at 2019-03-07 16:10:18 +0600
Processing by AnswersController#index as HTML
Parameters: {"question_id"=>"11"}
Question Load (1.4ms) SELECT "questions".* FROM "questions" WHERE "questions"."id" = $1 LIMIT $2 [["id", 11], ["LIMIT", 1]]
↳ app/controllers/answers_controller.rb:65
User Load (1.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 3], ["LIMIT", 1]]
↳ app/controllers/answers_controller.rb:6
Rendering answers/index.html.erb within layouts/application
Answer Load (1.3ms) SELECT "answers".* FROM "answers" WHERE "answers"."question_id" = $1 [["question_id", 11]]
↳ app/views/answers/index.html.erb:11
User Load (1.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 3], ["LIMIT", 1]]
↳ app/views/answers/_new.html.erb:7
Rendered answers/_new.html.erb (9.3ms)
Rendered answers/index.html.erb within layouts/application (18.5ms)
Completed 200 OK in 133ms (Views: 108.3ms | ActiveRecord: 18.4ms)
[Webpacker] Compilation failed:
Hash: 53a953077891e4cef2e8
Version: webpack 3.12.0
Time: 2928ms
Asset Size Chunks Chunk Names
application-c57a289721a93641de38.js 3.1 kB 0 [emitted] application
application-c57a289721a93641de38.js.map 2.49 kB 0 [emitted] application
manifest.json 142 bytes [emitted]
[0] ./app/javascript/packs/application.js 346 bytes {0} [built] [failed] [1 error]
ERROR in ./app/javascript/packs/application.js
Module build failed: SyntaxError: Unexpected token (14:15)
12 | if(window.railsEnv && window.railsEnv === 'development'){
13 | try {
> 14 | render(<App />, reactElement)
| ^
15 | } catch (e) {
16 | render(<RedBox error={e} />, reactElement)
17 | }
Completed 200 OK in 11715ms (Views: 11626.9ms | ActiveRecord: 27.7ms)
Started PATCH "/questions/11" for 127.0.0.1 at 2019-03-07 16:10:41 +0600
Processing by QuestionsController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"q7HQt4uGPwBIIz0icswfJLWMRk6MiopIfWu9JBcjkuX1VpGBdwlwZu903NDuebSaX8Y90VHnvcEoaV8unV2zkw==", "question"=>{"answer"=>{"answer_attributes"=>"This is the test answer to see how the information goes through", "user_id"=>"3", "question_id"=>"11"}}, "commit"=>"Post Your Answer", "id"=>"11"}
User Load (0.8ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 3], ["LIMIT", 1]]
↳ /Users/irina/.rvm/gems/ruby-2.6.0/gems/activerecord-5.2.2/lib/active_record/log_subscriber.rb:98
Question Load (0.5ms) SELECT "questions".* FROM "questions" WHERE "questions"."id" = $1 LIMIT $2 [["id", 11], ["LIMIT", 1]]
↳ app/controllers/questions_controller.rb:55
CACHE Question Load (0.0ms) SELECT "questions".* FROM "questions" WHERE "questions"."id" = $1 LIMIT $2 [["id", 11], ["LIMIT", 1]]
↳ app/controllers/questions_controller.rb:39
Unpermitted parameter: :answer
(0.5ms) BEGIN
↳ app/controllers/questions_controller.rb:40
User Load (0.7ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 3], ["LIMIT", 1]]
↳ app/controllers/questions_controller.rb:40
Answer Load (0.5ms) SELECT "answers".* FROM "answers" WHERE "answers"."question_id" = $1 [["question_id", 11]]
↳ app/controllers/questions_controller.rb:40
(0.3ms) COMMIT
↳ app/controllers/questions_controller.rb:40
Unpermitted parameter: :answer
(0.3ms) BEGIN
↳ app/controllers/questions_controller.rb:44
CACHE User Load (0.0ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 LIMIT $2 [["id", 3], ["LIMIT", 1]]
↳ app/controllers/questions_controller.rb:44
(0.4ms) ROLLBACK
↳ app/controllers/questions_controller.rb:44
Completed 500 Internal Server Error in 97ms (ActiveRecord: 8.3ms)
ActionController::UrlGenerationError (No route matches {:action=>"new", :controller=>"answers", :question_id=>nil}, missing required keys: [:question_id]):
app/controllers/questions_controller.rb:48:in `update'
UPDATE NO 2. It looks like because of this falsely set #answer the #question does not get saved as intended and the second part of the conditional kicks redirecting to the new_question_answer_path. I tried to update it to edit_question_answer_path and it gives the same error that no route matches.
If I open the answer in Pry I get the following object:
[1] pry(#<QuestionsController>)> #answer
=> #<Answer:0x00007fc3ec823c98
id: nil,
body: nil,
question_id: 11,
user_id: 3,
selected: nil,
created_at: nil,
updated_at: nil>
UPDATE No 3
Looks like changing my routes.rb to
Rails.application.routes.draw do
resources :questions, :has_many => :answers
root to: 'questions#index'
resources :questions do
resources :answers
end
devise_for :users
end
and also changing the form for the answer to this
<h2> Your Answer </h2>
<%= form_for [#question, Answer.new] do |form| %>
<div class="form-group">
<%=form.text_area :body, placeholder: "Add your answer", rows:10, class:"form-control" %><br>
<%=form.hidden_field :user_id, value: current_user.id, class:'d-none' %>
<%=form.hidden_field :question_id, value: #question.id %>
</div>
<div>
<%=form.submit 'Post Your Answer', class: 'btn-primary' %>
</div>
<% end %>
did the trick and helped to fix the problem. I am not sure if this is a perfect fix though)
Looks like changing my routes.rb to
Rails.application.routes.draw do
resources :questions, :has_many => :answers
root to: 'questions#index'
resources :questions do
resources :answers
end
devise_for :users
end
and also changing the form for the answer to this
<%= form_for [#question, Answer.new] do |form| %>
<div class="form-group">
<%=form.text_area :body, placeholder: "Add your answer", rows:10,
class:"form-control" %><br>
<%=form.hidden_field :user_id, value: current_user.id, class:'d-none' %>
<%=form.hidden_field :question_id, value: #question.id %>
</div>
<div>
<%=form.submit 'Post Your Answer', class: 'btn-primary' %>
</div>
<% end %>
did the trick and helped to fix the problem. I am not sure if this is a perfect fix though)
I have my form to save to my Stripe_account table. I recently nested the resources and now the form won't save to my database tables. I have it still working with the Stripe API and working there though.
What in my code is lacking?
User Model:
has_one :stripe_account
Stripe_account Model:
belongs_to :users
Stripe_account controller:
def new
#stripe_account = StripeAccount.new
#user = User.find(params[:user_id])
end
def create
#stripe_account = StripeAccount.new(stripe_account_params)
#user = User.find(params[:user_id])
acct = Stripe::Account.create({
.....
.....
#stripe_account.id = current_user.id
#stripe_account.acct_id = acct.id
respond_to do |format|
# #user = User.find(params[:id])
if #stripe_account.save
# current_user = #user
#user.stripe_account = acct.id
format.html { redirect_to new_bank_account_path, notice: 'Stripe account was successfully created.' }
format.json { render :show, status: :created, location: #stripe_account }
else
format.html { render :new }
format.json { render json: #stripe_account.errors, status: :unprocessable_entity }
end
end
end
View:
<%= form_for ([#user, #stripe_account]) do | f | %>
Routes:
resources :users do
resources :stripe_accounts
end
#added for testing
get 'stripe_' => "stripe_account#create"
get 'stripe_new' => "stripe_account#new"
Here's my routes maybe can help?: https://pastebin.com/RVWd2Qq9
Now even though I don't have the "bankaccount" controller or models set up correctly yet, shouldn't it be at least attempting to go there and saving the stripe_account? Just making sure that's not the issue. But it appears it's failing because a new form reloads.
The API is successfully going through as well and the accounts are appearing within stripe, just not my own database.
What in my programming is wrong?
Update to add cmd response:
Started POST "/users/2/stripe_accounts" for 127.0.0.1 at 2018-11-10 00:11:26 -0500
Processing by StripeAccountsController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"nz1234567890iJuFwsm/Z4ylhE6zoGdWN6QCfWtDZTH1sxZu/WCdWMKBGkc4zoZ2dOgk9c8UDwRzgqdxrT/sA==", "stripe_account"=>{"account_type"=>"individual", "business_name"=>"", "business_tax_id"=>"", "first_name"=>"Dill", "last_name"=>"Pickles", "ssn_last_4"=>"1234", "dob_month"=>"3", "dob_day"=>"4", "dob_year"=>"1917", "address_line1"=>"198 berry avenue", "address_city"=>"san fran", "address_state"=>"CA", "address_postal"=>"90213", "tos"=>"1", "id"=>"2"}, "full_account"=>"{:value=>\"true\"}", "button"=>"", "user_id"=>"2"}
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? ORDER BY "users"."id" ASC LIMIT ? [["id", 2], ["LIMIT", 1]]
↳ /home/bob/.rvm/gems/ruby-2.5.1/gems/activerecord-5.2.1/lib/active_record/log_subscriber.rb:98
User Load (0.2ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT ? [["id", 2], ["LIMIT", 1]]
↳ app/controllers/stripe_accounts_controller.rb:49
(0.1ms) begin transaction
↳ app/controllers/stripe_accounts_controller.rb:91
(0.1ms) rollback transaction
↳ app/controllers/stripe_accounts_controller.rb:91
Rendering stripe_accounts/new.html.erb within layouts/application
Rendered stripe_accounts/_account_form.html.erb (9.4ms)
Rendered stripe_accounts/new.html.erb within layouts/application (12.5ms)
Rendered layouts/_navbar.html.erb (1.9ms)
Rendered layouts/_footer.html.erb (0.4ms)
Completed 200 OK in 3202ms (Views: 190.0ms | ActiveRecord: 2.4ms)
Validation failed: User must exist
You can either use optional :true to resolve the error
#stipe_account.rb
belongs_to :user, optional: true
#^ should be singular
OR
Assign the user_id in the create action like so
#stripe_account.user_id = current_user.id #add this line
Update:
undefined method `user_id=' for StripeAccount:0x001234f4c58692ae8 Did
you mean? user="
The error is because you don't have user_id column in stripe_accounts table. Generate a migration that will do the job for you
rails g migration add_user_id_to_stripe_accounts user_id:integer
and do rails db:migrate
When a user creates a password update action is hit.
module Users
class PasswordController < ApplicationController
skip_before_action :authenticate_user!
before_action :set_user
def setup
render file: "#{Rails.root}/public/404" unless #user&.sign_in_count&.zero?
end
def update
if #user.update_attributes(password_params)
sign_in(:user, #user)
redirect_to root_path, notice: 'Setup complete'
else
flash[:alert] = errors(#user)
render :setup
end
end
private
def password_params
params.require(:user).permit(:password, :password_confirmation)
end
def set_user
#user = User.find_by(confirmation_token: params[:token])
end
end
end
When the update action is hit.
This is what the console shows
Started PATCH "/users/password/wynEjv-E7uFp44EcwjbS" for ::1 at 2017-02-07 12:33:01 +1000
Processing by Users::PasswordController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"vIyPtidsM1GDNLh3n7gDDB2HzvR0QEEwAAvfMybNRn0/t4em4StiUVDyKwLC9i1OThoYguEae4T+xqLttjt1Pw==", "email"=>"test04#example.com", "user"=>{"password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Continue", "token"=>"wynEjv-E7uFp44EcwjbS"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."confirmation_token" = $1 LIMIT $2 [["confirmation_token", "wynEjv-E7uFp44EcwjbS"], ["LIMIT", 1]]
(0.1ms) BEGIN
SQL (0.5ms) UPDATE "users" SET "encrypted_password" = $1, "updated_at" = $2 WHERE "users"."id" = $3 [["encrypted_password", "$2a$11$o5wmmxnCv.rlPha52GR0IOG4tbhEJYNNF9tctcSLDMS/dvLAU0hXq"], ["updated_at", 2017-02-07 02:33:01 UTC], ["id", 9]]
(1.0ms) COMMIT
User Load (0.4ms) SELECT "users".* FROM "users" WHERE "users"."id" = $1 ORDER BY "users"."id" ASC LIMIT $2 [["id", 9], ["LIMIT", 1]]
(0.1ms) BEGIN
(0.2ms) COMMIT
Completed 401 Unauthorized in 129ms (ActiveRecord: 2.5ms)
Does anyone know why the sign_in method isn't working here?
I used it on few apps and it worked then.
Thank you for any help in advance.
You can use it like this
#user.update_with_password(password_params)
sign_in #user, :bypass => true
Hope it will work for you as it worked for me!