Rails nomethod error on create action - ruby-on-rails

I have a create product page and an add photo page. Add photo page should add photos to a product that was just created.
I can get to add photo page /products/:product_id/pics(.:format) but I get an error on submit
ActiveRecord::RecordNotFound (Couldn't find Product without an ID):
photo controller
def create
#product = Product.find(params[:product_id]) # <--- error here
#photo = Photo.new
if #photo.valid?
#photo.product_id = #product.id
#photo.save!
respond_to do |format|
format.html { redirect_to product_path(#product) }
format.json { render json: #product }
end
else
redirect_to root_url, :notice => "Somehting went wrong!"
end
end
pics.html.haml
= form_for #photo, :html => { :multipart => true, :id => "fileupload" } do |f|
= f.file_field :upload
products controller
def pics
#product = Product.find(params[:product_id])
#photo = Photo.new
# #product.photos.build
end
full console error
Started POST "/photos" for 127.0.0.1 at 2013-07-09 02:11:11 -0400
Processing by PhotosController#create as JSON
Parameters: {"utf8"=>"✓", "authenticity_token"=>"K9jWB2D0bFUB5+KOCRKLUsuDGNLchjzCBCL1h1znOiQ=", "photo"=>{"upload"=>#>}}
Completed 404 Not Found in 1ms
ActiveRecord::RecordNotFound (Couldn't find Product without an ID):
app/controllers/photos_controller.rb:15:in `create'
console with sachins solution
Started POST "/photos" for 127.0.0.1 at 2013-07-09 02:55:25 -0400
Processing by PhotosController#create as JSON
Parameters: {"utf8"=>"✓", "authenticity_token"=>"5RV+GUCvNEFrw7l3/ApqAlbK/XJP78LmDR2Hc+O0rQ0=", "product_id"=>"125", "photo"=>{"upload"=>#>}}
Product Load (0.1ms) SELECT "products".* FROM "products" WHERE "products"."id" = ? LIMIT 1 [["id", "125"]]
Redirected to http://google.com/
Completed 302 Found in 4ms (ActiveRecord: 0.1ms)
Started GET "/" for 127.0.0.1 at 2013-07-09 02:55:25 -0400
Processing by StaticPagesController#home as JSON
Rendered static_pages/home.html.haml within layouts/application (0.1ms)
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."auth_token" IS NULL LIMIT 1
Completed 200 OK in 93ms (Views: 91.8ms | ActiveRecord: 0.3ms)

try this out: ---
photos controller
def new
#product = Product.find(params[:product_id])
#photo = Photo.new
#photo.product_id = #product.id
end
pics.html.haml
= form_for #photo, :html => { :multipart => true, :id => "fileupload" } do |f|
= f.file_field :upload
= hidden_field_tag 'product_id', #photo.product_id

Use form_for [#product, #photo] instead of just #photo in your form. Be sure to, of course, find the product using params[:product_id].
You need to nest your routes like this:
resources :products do
resources :photos
end
Otherwise you won't have a params[:product_id] on your request.

try in your form
form_for [#product, #photo]

error is there in accessing the product_id from params
use params[:product_id] instead params[:product][:product_id]

Just set the hidden_field_tag in form_for
eg:-
= hidden_field_tag 'product_id', #product.id

Related

redirect_to inside controller action doesn't work

I use Rails 5.1 and the "redirect_to #search" inside create action doesn't work.
My SearchesController:
class SearchesController < ApplicationController
def new
#search = Search.new
end
def create
#search = Search.create!(search_params)
redirect_to #search # search_path(#search) doesn't work either
end
def show
#search = Search.find(params[:id])
end
private
def search_params
params.require(:search).permit!
end
end
After creating a new search entry by clicking the submit button it doesn't redirect to show page.
My app/views/searches/new.html.erb:
<div>
<h1>Advanced Search Form</h1>
<%= form_with model: #search do |form| %>
<%= form.text_field :keywords %>
<%= form.select :ort, options_from_collection_for_select(Imagecapturing.cities, :ort, :city_name, prompt: false, include_blank: false) %>
<%= form.submit("Suchen", :id=>"button", :class=>"Test", :name=>"submit") %>
<% end %>
</div>
config/routes.rb:
Rails.application.routes.draw do
root 'imagecapturings#index'
resources :searches
end
Log:
Started POST "/searches" for ::1 at 2018-06-14 17:37:54 +0200
Processing by SearchesController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"B91lIUxZZvanOx1luhhfWBJ9mAO5Np/6Bx4xzPdv2Ygj29bprWk5+wIBP7kMVl5Eoxz0KcyJF5DK8UaVUhQaFQ==", "search"=>{"keywords"=>"", "ort"=>"A-St. Paul"}, "submit"=>"Suchen"}
(0.6ms) BEGIN
SQL (22.8ms) INSERT INTO `searches` (`keywords`, `ort`, `created_at`, `updated_at`) VALUES ('', 'A-St. Paul', '2018-06-14 15:37:58', '2018-06-14 15:37:58')
(11.1ms) COMMIT
Redirected to http://localhost:4000/searches/23
Completed 302 Found in 50ms (ActiveRecord: 34.5ms)
Started GET "/searches/23" for ::1 at 2018-06-14 17:37:58 +0200
Processing by SearchesController#show as JS
Parameters: {"id"=>"23"}
Search Load (0.7ms) SELECT `searches`.* FROM `searches` WHERE `searches`.`id` = 23 LIMIT 1
Rendering searches/show.html.erb within layouts/application
Imagecapturing Load (10.4ms) SELECT `imagecapturing`.* FROM `imagecapturing` WHERE (ort LIKE '%A-St. Paul%') ORDER BY `imagecapturing`.`id` DESC
Rendered searches/show.html.erb within layouts/application (62.5ms)
Rendered layouts/_top_nav.html.erb (6.0ms)
Imagecapturing Load (17.0ms) SELECT distinct(ort) FROM `imagecapturing` ORDER BY `imagecapturing`.`ort` ASC
Rendered searches/_links.html.erb (33.5ms)
Completed 200 OK in 409ms (Views: 340.1ms | ActiveRecord: 28.0ms)
Is in "Processing by SearchesController#show as JS" the "as JS" part the issue?
How can I get the redirect working so that after clicking the submit button it redirects to the show action?
--- UPDATE
With suggestion of user Rockwell I modified the create action to:
def create
#search= Search.create!(search_params)
respond_to do |format|
if #search
format.html {redirect_to #search}
format.json { render :show, status: :created, location: #step }
format.js { redirect_to #search }
else
format.html { render :new }
format.json { render json: #search.errors, status: :unprocessable_entity }
format.js { render :new }
end
end
end
But it still processes "as JS":
Started POST "/searches" for ::1 at 2018-06-14 18:09:18 +0200
Processing by SearchesController#create as JS
Parameters: {"utf8"=>"✓", "authenticity_token"=>"D7l5ibv8hu08Z18VKqa0Y+iqGHfT+SIZTIoM8vHdcpArv8pBWszZ4Jldfcmc6LV/Wct0XaZGqnOBZXurVKaxDQ==", "search"=>{"keywords"=>"", "ort"=>"Cologny"}, "submit"=>"Suchen"}
(0.2ms) BEGIN
SQL (11.8ms) INSERT INTO `searches` (`keywords`, `ort`, `created_at`, `updated_at`) VALUES ('', 'Cologny', '2018-06-14 16:09:18', '2018-06-14 16:09:18')
(17.0ms) COMMIT
Redirected to http://localhost:4000/searches/30
Completed 302 Found in 36ms (ActiveRecord: 29.0ms)
Started GET "/searches/30" for ::1 at 2018-06-14 18:09:19 +0200
Processing by SearchesController#show as JS
Parameters: {"id"=>"30"}
Search Load (0.8ms) SELECT `searches`.* FROM `searches` WHERE `searches`.`id` = 30 LIMIT 1
Rendering searches/show.html.erb within layouts/application
Imagecapturing Load (28.1ms) SELECT `imagecapturing`.* FROM `imagecapturing` WHERE (ort LIKE '%Cologny%') ORDER BY `imagecapturing`.`id` DESC
Rendered searches/show.html.erb within layouts/application (16157.3ms)
Rendered layouts/_top_nav.html.erb (3.6ms)
Imagecapturing Load (27.6ms) SELECT distinct(ort) FROM `imagecapturing` ORDER BY `imagecapturing`.`ort` ASC
Rendered searches/_links.html.erb (39.2ms)
Completed 200 OK in 16404ms (Views: 16314.1ms | ActiveRecord: 56.5ms)
I believe that you are correct, the Processing by SearchesController#show as JS is what is causing your error. If you respond to the format it should solve your issue. I added HTML and JSON here but you wouldn't need to if you know you will never need that, just the js should be fine.
def create
#search = Search.new(search_params)
respond_to do |format|
if #search.save
format.html {redirect_to #search}
format.json { render :show, status: :created, location: #step }
format.js { redirect_to #search }
else
format.html { render :new }
format.json { render json: #search.errors, status: :unprocessable_entity }
format.js { render :new }
end
end
end
If you are sending this as an AJAX you could specify the type that gets sent as well, but I would need to see the JS code for that to give a solution to fix that.
it is working as expected, you can see it on the log, the insert is done and then the redirect too.
but the problem is the format you are asking. it seems like the create is called as js Processing by SearchesController#create as JS (maybe you are doing an ajax request with that format or your form has remote:true). and then the redirect isn't done visually of course. you need to make the create request without js format or don't make the redirect on the controller and create a "create.js" view that does the redirect. but of course it's not the best solution.
if you want to do the redirect, the best way is to change the format of the create request.

Ruby on Rails: New post not saving on the blog

I'm working on an exercise, creating a blog with ruby on rails. I have the form ready to post an article, but once I click on the submit button, I am redirected to the homepage but the article doesn't save. Here is the following code
class ArticlesController < ApplicationController
def index
#articles = Article.paginate(:page => params[:page], per_page: 5).order('created_at DESC')
end
def show
#article = Article.find(params[:id])
end
def new
#article = Article.new
end
def create
#article = Article.new(title: params.permit[:title], body: params.permit[:body])
if #article.save
redirect_to articles, :notice => "Your post has been saved"
else
render :create
end
end
end
Here is the view create.html.haml
.container
.row
.col-xs-9-
.panel-title
%h2 Ecrivez votre article
= form_for #article do |f|
= f.text_field :title
= f.text_area :body, size: "60x12"
= f.submit "Publier"
Then the route.rb, I don't know if it can help
TP2::Application.routes.draw do
resources :articles, only: [:index]
get 'articles' => 'articles#index'
get 'articles/:id' => 'articles#show'
get 'articles/new'
get 'post' => 'articles#create'
post 'articles' => 'articles#index'
And to finish here is what the console show when I try to post an article
Started GET "/post" for 127.0.0.1 at 2016-04-10 14:24:56 +0200
Processing by ArticlesController#create as HTML
(0.2ms) BEGIN
(0.2ms) ROLLBACK
Rendered articles/create.html.haml within layouts/application (1.4ms)
Completed 200 OK in 9ms (Views: 4.9ms | ActiveRecord: 0.4ms)
Started POST "/articles" for 127.0.0.1 at 2016-04-10 14:25:10 +0200
Processing by ArticlesController#index as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"FMQmKvZ1t98ZE21VaiBQhm0jKJ9x9BwkXFbh4obfi3Qea0Zax5dgGirfpgcAiQA464GMD2+Qv/eGYrmvEoTZBQ==", "article"=>{"title"=>"Post", "body"=>"New Article test"}, "commit"=>"Publier"}
Article Load (0.6ms) SELECT "articles".* FROM "articles" ORDER BY created_at DESC LIMIT 5 OFFSET 0
(0.4ms) SELECT COUNT(*) FROM "articles"
Rendered articles/index.html.haml within layouts/application (3.4ms)
Completed 200 OK in 7ms (Views: 5.3ms | ActiveRecord: 1.0ms)
I don't understand why the new article won't save. Does anyone understand why ?
I would simplify the routes:
Rails.application.routes.draw do
root to: 'articles#index' # or where you want for the first page
resources :articles #will give you the correct path and verbs
end
And the articles_controller.rb
class ArticlesController < ApplicationController
...
def create
#article = Article.new(article_params)
respond_to do |format|
if #article.save
format.html { redirect_to #article, notice: "Article created!" }
else
format.html { render action: 'new' }
end
end
end
private
def article_params
params.require(:article).permit(:title, :body)
end
end
Because you are learning new stuff, this is a way you should use to debug your code:
put a binding.pry (a breakpoint) on the line before #article.save (or use another debugger, you can find it on Github)
reload your page, input the fields and click Save
go to the rails console, issue #article.save on the console (or #article.valid?), it should return false
puts #article.errors, so you can what are the validation issues
Good luck :)

Rails create method to post object not working

I'm new to working with rails. I created a article posting form and when I click the post button it brings me to the articles page but it's not posting what I typed.
routes.rb:
get 'articles/new' => 'articles#new'
post 'articles' => 'articles#create'
articles_controller.rb:
class ArticlesController < ApplicationController
def index
#articles = Article.all
end
def new
#article = Article.new
end
def create
#article = Article.new(article_params)
if #article.save
redirect_to '/articles'
else
render 'new'
end
end
private
def article_params
params.required(:article).permit(:content)
end
end
`articles/new.html.erb`:
<div class="create">
<div class="container-fluid">
<%= form_for #article do |t| %>
<%= t.text_field :title, :placeholder => 'Title', :class => 'article_title' %>
<%= t.text_area :body, :placeholder => 'Article', :class => 'article_body' %>
<%= t.submit 'Post', :class => 'btn-btn-article' %>
<% end %>
</div>
</div>
Server log:
Started POST "/articles" for 127.0.0.1 at 2015-10-29 00:43:30 -0400
Processing by ArticlesController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"c49EXOKfsDP6l2xuquvmUncgTAvXIXpylgx5qK+LvCSrPFvuS37zgR9Cv/BDVwMkCFSYcaWbM+3+qpZazQby8g==", "article"=>{"title"=>"Test", "body"=>"Tsting"}, "commit"=>"Post"}
Unpermitted parameters: title, body
[1m[36m (0.1ms)[0m [1mBEGIN[0m
[1m[35mSQL (0.2ms)[0m INSERT INTO `articles` (`created_at`, `updated_at`) VALUES ('2015-10-29 04:43:30', '2015-10-29 04:43:30')
[1m[36m (11.0ms)[0m [1mCOMMIT[0m
Redirected to http://localhost:3000/articles
Completed 302 Found in 14ms (ActiveRecord: 11.3ms)
Started GET "/articles" for 127.0.0.1 at 2015-10-29 00:43:30 -0400
Processing by ArticlesController#index as HTML
Rendered articles/index.erb within layouts/application (0.0ms)
Completed 200 OK in 32ms (Views: 31.5ms | ActiveRecord: 0.0ms)
Started GET "/" for 127.0.0.1 at 2015-10-29 00:51:17 -0400
Processing by HomeController#home as HTML
Rendered home/home.erb within layouts/application (0.5ms)
Completed 200 OK in 31ms (Views: 30.1ms | ActiveRecord: 0.0ms)
Started GET "/" for 127.0.0.1 at 2015-10-29 00:51:21 -0400
Processing by HomeController#home as HTML
Rendered home/home.erb within layouts/application (0.2ms)
Completed 200 OK in 30ms (Views: 29.1ms | ActiveRecord: 0.0ms)
Started GET "/" for 127.0.0.1 at 2015-10-29 00:51:22 -0400
Processing by HomeController#home as HTML
Rendered home/home.erb within layouts/application (0.6ms)
Completed 200 OK in 96ms (Views: 94.8ms | ActiveRecord: 0.0ms)
Started GET "/articles/new" for 127.0.0.1 at 2015-10-29 00:51:29 -0400
Processing by ArticlesController#new as HTML
Rendered articles/new.erb within layouts/application (1.0ms)
Completed 200 OK in 86ms (Views: 85.2ms | ActiveRecord: 0.0ms)
So, your server log is telling you the problem:
Unpermitted parameters: title, body
You have to whitelist your title and body attributes as Action Controller parameters are forbidden to be used in Active Model mass assignments until they have been whitelisted.
Change:
def article_params
params.required(:article).permit(:content)
end
To:
def article_params
params.require(:article).permit(:title, :body)
end
Also, take a look at the official Rails documentation for Strong Parameters
Update
I would suggest you to use RESTful route in your routes file:
resources :articles
Then, you will have this route:
articles GET /articles(.:format) articles#index
Then, in your controller's create action, you can use articles_path:
def create
#article = Article.new(article_params)
if #article.save
redirect_to articles_path
else
render 'new'
end
end
Unpermitted parameters: title, body
You should change your article_params to below
def article_params
params.require(:article).permit(:title, :body)
end
It says in your log -
Unpermitted parameters: title, body
Change your article_params method to
def article_params
params.require(:article).permit(:title, :body, :content)
end

RoR; Object expected got string

I found several topics related , but couldn't figure out how to solve this problem,
This is my code
<%= f.label :projeto %><br>
<%= f.collection_select :projeto, Projeto.order(:id), :id, :name, include_blank: true %>
model => task belongs_to projeto and projeto has_many tasks
Full Error:
ActiveRecord::AssociationTypeMismatch at /tasks/1
Projeto(#69996814678740) expected, got String(#69996762580840)
Database is set to t.references.
Task_controller
def update
respond_to do |format|
if #task.update(task_params)
format.html { redirect_to #task, notice: 'Task was successfully updated.' }
format.json { render :show, status: :ok, location: #task }
else
format.html { render :edit }
format.json { render json: #task.errors, status: :unprocessable_entity }
end
end
end
def task_params
params.require(:task).permit(:seq, :descr, :seqpai, :typo, :hour, :projeto)
end
Started PATCH "/tasks/1" for 127.0.0.1 at 2015-06-18 14:30:23 -0300
Processing by TasksController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"Is7YTC0v5OONEEsIgOvmI+CEuVYG/WsoKWzskGippD2eOwthKVHb2dI+S19GkkI9aU0IwTrzwERlLq2ybWbGxw==", "task"=>{"seq"=>"0", "descr"=>"Projeto", "seqpai"=>"", "typo"=>"Analitica", "hour"=>"12", "projeto"=>"1"}, "commit"=>"Update Task", "id"=>"1"}
User Load (0.3ms) SELECT "users".* FROM "users" WHERE "users"."id" = ? LIMIT 1 [["id", 1]]
Task Load (0.2ms) SELECT "tasks".* FROM "tasks" WHERE "tasks"."id" = ? LIMIT 1 [["id", 1]]
(0.2ms) begin transaction
(0.1ms) rollback transaction
Completed 500 Internal Server Error in 25ms (ActiveRecord: 0.8ms)
Normally this is caused by assigning a string to something expecting a model association. For example:
# Not allowed, `project=` expects a Project model
#task.project = params[:project_id]
# Converts parameter into model, but may throw exception
#task.project = Project.find(params[:project_id])
# Direct assignment, requires validation on model level
#task.project_id = params[:project_id]
I changed the View for
<%= f.label :projeto_id %>
and permited in controller projeto_id
Then worked Fine,
Thanks everyone for the hint.

How to allow devise users to edit their profil?

I have a namespace called "backend" which is protected by Devise.
I would like now to allow users to edit their profil.
So I created a users_controller in Backend.
Here's the users_controllercode :
class Backend::UsersController < ApplicationController
layout 'admin'
before_filter :authenticate_user!
def index
#users = Backend::User.all
respond_to do |format|
format.html # index.html.erb
format.json { render json: #users }
end
end
def show
#user = Backend::User.find(params[:id])
respond_to do |format|
format.html # show.html.erb
format.json { render json: #user }
end
end
def edit
#user = Backend::User.find(params[:id])
end
def update
#user = Backend::User.find(params[:id])
respond_to do |format|
if #user.update_attributes(params[:user])
format.html { redirect_to #user, notice: 'Article was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
end
When I go on backend_users_path there is a list of all the users. I would like to permit to edit only his own profil.
So I go on the Edit page : <%= link_to "Edit", edit_backend_user_path(backend_user.id) %> .
Here's the Edit page code :
<%= simple_form_for #user do |f| %>
<div><%= f.label :email %><br />
<%= f.input :email, :autofocus => true %></div>
<div><%= f.submit "Update" %></div>
<% end %>
And there is my problem : when I try to modify the email address, nothing happen. The update fails.
How can I do this ?
I'm quite lost.
Thanks by advance.
Here's the log file :
Started PUT "/backend/users/1" for 127.0.0.1 at 2012-11-13 12:13:51 +0100
Processing by Backend::UsersController#update as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"wWrUDh7LVWhP+P7OWO6laDWaCKInxk37AA2BPuQWAI4=", "backend_user"=>{"email"=>"grellazzi#laposte.net"}, "commit"=>"Update", "id"=>"1"}
[1m[35mBackend::User Load (0.0ms)[0m SELECT `backend_users`.* FROM `backend_users` WHERE `backend_users`.`id` = 1 LIMIT 1
[1m[36mBackend::User Load (0.0ms)[0m [1mSELECT `backend_users`.* FROM `backend_users` WHERE `backend_users`.`id` = ? LIMIT 1[0m [["id", "1"]]
[1m[35mSQL (1.0ms)[0m BEGIN
[1m[36m (0.0ms)[0m [1mCOMMIT[0m
Redirected to http://localhost:3000/backend/users/1
Completed 302 Found in 23ms (ActiveRecord: 1.0ms)
Started GET "/backend/users/1" for 127.0.0.1 at 2012-11-13 12:13:51 +0100
Processing by Backend::UsersController#show as HTML
Parameters: {"id"=>"1"}
[1m[35mBackend::User Load (0.0ms)[0m SELECT `backend_users`.* FROM `backend_users` WHERE `backend_users`.`id` = 1 LIMIT 1
[1m[36mBackend::User Load (0.0ms)[0m [1mSELECT `backend_users`.* FROM `backend_users` WHERE `backend_users`.`id` = ? LIMIT 1[0m [["id", "1"]]
Rendered backend/users/show.html.erb within layouts/admin (0.0ms)
Completed 200 OK in 7ms (Views: 5.0ms | ActiveRecord: 0.0ms)
Thanks for your links, I tried to modify my user_controller with
if params[:user][:password].blank?
params[:user].delete("password")
params[:user].delete("password_confirmation")
end
#user = User.find(current_user.id)
if #user.update_attributes(params[:user])
# Sign in the user bypassing validation in case his password changed
sign_in #user, :bypass => true
redirect_to root_path
else
render "edit"
end
But it fails...
If nothing happens, that usually indicates a validation error, in your case probably a missing password or other data that is not part of your form but is still being validated. To debug this, output #user.errors.inspect to your logfile or look at error_messages_on #user in your view.
In general, take a look at these guides on how to allow users to edit their (partial) profile:
https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-edit-their-account-without-providing-a-password
https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-edit-their-password

Resources