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
Related
I'm currently working on a Rails 7.0.3.1 application. I have a controller ApplicationController where I have a before_action filter to authenticate that a user is logged in. If the user is not logged in I redirect to the sign in form.
class ApplicationController < ActionController::Base
before_action :authorize
protect_from_forgery with: :exception
helper_method :current_user, :logged_in?
private
def current_user
#current_user ||= PropertyOwner.find_by(id: session[:user_id])
end
def logged_in?
if #current_user
true
else
false
end
end
def authorized
return if logged_in?
redirect_to sessions_new_path
end
end
The sessions_new_path redirects to the log in form in /sessions/new.html.erb template. In the SessionsController, If a user is authenticated I redirect to the properties_path However, after I log in Im redirected to the login page again instead of being redirected to the /properties page.
class SessionsController < ApplicationController
skip_before_action :authorized
def create
user = PropertyOwner.find_by(email: params[:email])
if user&.authenticate(params[:password])
session[:user_id] = user.id
redirect_to properties_path, status: :see_other
else
redirect_to sessions_new_path, notice: "Invalid email or password"
end
end
def destroy
session.delete(:user_id)
redirect_to sessions_new_path, status: :see_other, notice: 'Logged out!'
end
end
In the line where I run redirect_to properties_path, status: :see_other I set status: :see_other since in Rails 7 is making a TURBO_STREAM request. When I look into the server I see that there is a message
Filter chain halted as :authorized rendered or redirected
On the GET request to the /properties route. and then is redirected to the sessions/new path, why is that?
Processing by SessionsController#new as HTML
Rendering layout layouts/application.html.erb
Rendering sessions/new.html.erb within layouts/application
Rendered sessions/new.html.erb within layouts/application (Duration: 4.5ms | Allocations: 2893)
Rendered layout layouts/application.html.erb (Duration: 7.9ms | Allocations: 6241)
Completed 200 OK in 16ms (Views: 10.7ms | ActiveRecord: 0.0ms | Allocations: 8945)
Started POST "/sessions" for ::1 at 2022-12-29 16:51:28 -0500
Processing by SessionsController#create as TURBO_STREAM
Parameters: {"authenticity_token"=>"[FILTERED]", "email"=>"example#example.com", "password"=>"[FILTERED]", "commit"=>"Sign In"}
PropertyOwner Load (0.6ms) SELECT "property_owners".* FROM "property_owners" WHERE "property_owners"."email" = $1 LIMIT $2 [["email", "example#example.com"], ["LIMIT", 1]]
↳ app/controllers/sessions_controller.rb:5:in `create'
Redirected to http://localhost:3000/properties
Completed 303 See Other in 264ms (ActiveRecord: 9.2ms | Allocations: 10088)
Started GET "/properties" for ::1 at 2022-12-29 16:51:28 -0500
Processing by PropertiesController#index as TURBO_STREAM
Redirected to http://localhost:3000/sessions/new
Filter chain halted as :authorized rendered or redirected
Completed 302 Found in 1ms (ActiveRecord: 0.0ms | Allocations: 314)
Started GET "/sessions/new" for ::1 at 2022-12-29 16:51:28 -0500
Processing by SessionsController#new as TURBO_STREAM
Rendering layout layouts/application.html.erb
Rendering sessions/new.html.erb within layouts/application
Rendered sessions/new.html.erb within layouts/application (Duration: 1.1ms | Allocations: 1585)
Rendered layout layouts/application.html.erb (Duration: 1.9ms | Allocations: 2426)
Completed 200 OK in 3ms (Views: 2.5ms | ActiveRecord: 0.0ms | Allocations: 2787)
Not sure why is redirecting to the log in page again after being redirected to properties, I never hit the PropertiesController. Any idea why?
logged_in? is always false when it's called, because #current_user is not initialized and is nil by default.
def logged_in?
if #current_user
Make sure to always use current_user:
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
helper_method :current_user
# NOTE: to avoid confusion, authorization is not authentication.
# before_action :authorized
before_action :authenticate
private
def current_user
#current_user ||= PropertyOwner.find_by(id: session[:user_id])
end
# def logged_in?
# current_user.present?
# end
def authenticate
# there is really no need for explicit `true` or `false`
return if current_user
redirect_to sessions_new_path
end
end
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
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.
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 :)
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