Rails: ActionController::InvalidAuthenticityToken when adding a Image - ruby-on-rails

I am new to Ruby-on-rails and I am currently working on a project that let a user log in to add,create update delete a Marvel character. Each characters have a name, description, origin, alliance and image.
I used Carrierwave for file upload.
I used the scaffold command and everything was working fine, until I decided to be able to create and update my characters on the same page using .js.erb files instead of having to redirect the user to 2 different pages for the create and the update.
I have the following error everytime I try to create a character with a image. everything works fine when I don't add a image:
ActionController::InvalidAuthenticityToken
I know that there are a few different other similar questions already asked on the forum but I can't seem to find the answer to my problem.
I am using Rails 4.2.6.
I tried to add the gem remotipart but it didn't fix my issue.
create.js.erb code:
$("#characters").append("<%= escape_javascript(render #character)%>");
create action in the controller:
def create
#character = Character.new(character_params)
respond_to do |format|
if #character.save
format.html { redirect_to #character, notice: 'Character was successfully created.' }
format.json { render :show, status: :created, location: #character }
format.js
else
format.html { render :new }
format.json { render json: #character.errors, status: :unprocessable_entity }
end
end
end
I hope I provide enough information, thanks in advance!
Edit:
Here is the code I have in the form.html.erb that let the users add a image:
<div class="field">
<%= f.label :image %>
<%= f.file_field :image %>
<% if f.object.image %>
<%= image_tag f.object.image.url %>
<!--<%= f.label :remove_image %>
<%= f.check_box :remove_image %> -->
<% end %>
</div>

I think your Rails forms now will not render the CSRF field in the form:
<%= form_for #character, :remote => true, :authenticity_token => true,:multipart => true do |f| %>
.....
<% end %>

skip_before_action :verify_authenticity_token
Put this in your controller

Related

Rails remote form collection_select onchange error

I'm trying to have a remote form automatically submit when a select option is changed. Everything works when I remove remote: true from the form tag, except I don't want the page to reload each time.
I am using Rails 5.1.4.
Code
<%= form_for #foo, remote: true do |f| %>
... fields
<%= f.collection_select :bar_id, #list, :id, :name,
{include_blank: '-'}, { onchange: 'this.form.submit();'} %>
<% end %>
Controller
def update
respond_to do |format|
if #foo.update(foo_params)
format.html { redirect_to #foo }
format.json { render :show, status: :ok, location: #foo }
else
format.html { render :edit }
format.json { render json: #foo.errors, status: :unprocessable_entity }
end
end
end
I'm getting the following error when the selection is updated in the view:
ActionController::InvalidAuthenticityToken
I'm assuming the this.form.submit(); is the problem. How can I get this form to submit successfully?
Try to the following simple way adding authenticity_token: true to your form tag like below
<%= form_for #foo, remote: true, authenticity_token: true do |f| %>
It should work, at least working for me.
Updated After Comment
You need to work with partial if you use remote: true like if your form in new.html.erb then cut out form part and create a partial for the form like _form.html.erb then render this into new.html.erb like
new.html.erb
<div id="my-form">
<%= render partial: "form" %>
</div>
and the create a js.erb file based your main file like new.js.erb and put this line like
$("#my-form").html("<%= escape_javascript(render("form")) %>");
On your controller add format.js like below
format.html { redirect_to #foo }
format.js
format.json { render :show, status: :ok, location: #foo }
For complete jQuery/AJAX reference with RoR-5 you can read this tutorial it will help to brush up your jQuery/AJAX skill
Hope that will work
add this line to your form.
<%= tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token) %>
and your form should be like this:
<%= form_for #foo, remote: true do |f| %>
<%= tag(:input, :type => "hidden", :name => request_forgery_protection_token.to_s, :value => form_authenticity_token) %>
... fields
<%= f.collection_select :bar_id, #list, :id, :name,
{include_blank: '-'}, { onchange: 'this.form.submit();'} %>
<% end %>
The authenticity token is a random value generated in your view to prove a request is submitted from a form on your site, not somewhere else. This protects against CSRF attacks
You can avoid above error by two ways
1) Add following code in application controller
skip_before_filter :verify_authenticity_token
Reference Link: http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection/ClassMethods.html
2) Add authenticity_token in the form
<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
OR <%= csrf_meta_tags %>

Form hidden fields and security

I m using hidden field in my app to add user_id to my database "Camping". I have associations "User" has many campings and "Camping" belongs_to "user".
When I run firebug or something like this, I can modify user_id value of this field. If any user puts his ID, I can modify object to other user... I want to avoid this !
My code
<%= f.hidden_field :user_id, :value => current_user.id %>
This code, is necessary because I allow only user to edit / updated / create object if they have user_id == current_user.id.
How to fix this security problem ?
By the way, I m using devise.
Edit with full code
My _form.html.erb
<%= form_for(camping) do |f| %>
<% if camping.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(camping.errors.count, "error") %> prohibited this camping from being saved:</h2>
<ul>
<% camping.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.hidden_field :user_id, :value => current_user.id %>
<div class="form-group">
<label for="name">Nom du camping</label>
<%= f.text_field :name, autofocus: true, class:"form-control", id:"name", :required => true%>
</div>
<div class="actions">
<%= f.submit "Enregistrer", class:"btn btn-success" %>
</div>
<% end %>
my controller
def new
#camping = Camping.new
#campings = Camping.all
end
def edit
end
def create
#camping = Camping.new(camping_params)
respond_to do |format|
if #camping.save
format.html { redirect_to #camping, notice: 'Camping was successfully created.' }
format.json { render :show, status: :created, location: #camping }
else
format.html { render :new }
format.json { render json: #camping.errors, status: :unprocessable_entity }
end
end
end
def update
#camping = Camping.find(params[:id])
respond_to do |format|
if #camping.update(camping_params)
format.html { redirect_to #camping, notice: 'Camping was successfully updated.' }
format.json { render :show, status: :ok, location: #camping }
else
format.html { render :edit }
format.json { render json: #camping.errors, status: :unprocessable_entity }
end
end
end
my edit.html.erb
<div class="containershow">
<h1>Editing Camping</h1>
<%= render 'form', camping: #camping %>
<%= link_to 'Show', #camping %> |
<%= link_to 'Back', campings_path %>
</div>
my new.html.erb
<h1>New Camping</h1>
<%= render 'form', camping: #camping %>
<%= link_to 'Back', campings_path %>
Edit solution ?
User can create and update his camping. I delete hidden_field
def create
# #camping = Camping.new(camping_params)
#camping = Camping.new((camping_params).merge(:user_id => current_user.id))
respond_to do |format|
if #camping.save
format.html { redirect_to #camping, notice: 'Camping was successfully created.' }
format.json { render :show, status: :created, location: #camping }
else
format.html { render :new }
format.json { render json: #camping.errors, status: :unprocessable_entity }
end
end
end
In Devise, the current user object is in current_user, available to your controllers. When saving the model, make sure to fill the user id field from that object, and not user input in the update action of your controller. Note that the edit action does not matter, that just renders the edit page, the actual update happens in update (if you follow the default conventions). Of course if you don't want users to even see other users' objects, you also need access control in other controller actions like edit as well, but that (implementing access control in a multi-tenant Rails application) is a different and much broader question.
More generally, be aware that anything that comes from a request can very easily be forged by a user. Always implement security server-side and do not trust user input!
Edit (seeing your code)
To prevent users updating others' Campings, you need to check in update after getting the #camping object (the second line) whether that's a camping object that your logged on user (current_user.id) is supposed to be able to edit.
The same way, if you want to prevent users from creating Campings for other users, you need to make sure in create that user_id will be set to the current user, something like #camping.user_id=current_user.id.
Similarly, if you want to prevent having a look at each other's Campings, you need to add checks to edit, show and pretty much all actions that return such objects.
There are gems like cancan and cancancan that may help with access control in Rails, they are worth a look!
Your Question is quite interesting but simple In the any HTML View Any one can change anything this will cause a security wise vulnerability as well.
To avoid these issues we need to authenticate it by two way You have to check the code by like It should be use by Controller not by view.
Suppose If you are creating any article of particular user
So To avoid it what you can do You can set the User ID in Session and make a Helper Method to find Current User always
So that you can find current user directly from controller and create article according to user
def Create
#article = current_user.articles.create(article_params)
end
This kind of Two way checking you can put up so that It will be safe.
To avoid the spend time on these work you can use gem directly like Devise

Rendering a partial from one controller to another below content

In my views, I have comments/_form.html.erb, and there is another controller views for post posts/show.html. I want to render comments/_form.html.erb in posts/show.html, which shows an individual post and comments associated with that post, and it is all set and working fine.
I want to provide ability to comment and render that partial below these comments so that we can make new comment on the same posts/show.html page instead of navigating to comments/new.html.erb page. I am using nested resources like:
resources :posts do
resources :comments
end
In my comments/new.html.erb, I am doing this:
<%= form_for([:post, #comment]) do |f| %>
....
<% end %>
How should I render it in my posts/show.html.erb page?
Javascript is the missing piece in your puzzle. Essentially you'll do 3 things.
Make sure your form is using js to submit (remote)
Make sure your controller responds to js input
Create a js.erb file that will append each new comment
Implementation notes:
I would probably do something like this:
Add the form to the view, and add an element that wraps around the comments, in this case, I used ul#comments
# app/views/posts/show.html.erb
<p>
<strong>Title:</strong>
<%= #post.title %>
</p>
<p>
<strong>Body:</strong>
<%= #post.body %>
</p>
<br/>
<ul id="comments">
<%= render #comments %>
</ul>
<%= form_for [#post, #new_comment], remote: true do |f| %>
<%= f.text_field :body %>
<%= f.submit %>
<%end%>
Add the js response in the controller
# app/controllers/comments_controller.rb
def create
#post = Post.find params[:post_id]
#comment = #post.comments.new(comment_params)
#new_comment = #post.comments.new(comment_params)
respond_to do |format|
if #comment.save
format.html { redirect_to [#post, #comment], notice: 'Comment was successfully created.' }
format.json { render :show, status: :created, location: #comment }
format.js
else
format.html { render :new }
format.json { render json: #comment.errors, status: :unprocessable_entity }
end
end
end
Then add a ujs file to make your changes on the fly (this does 2 things, adds a new comment and empties the form).
# app/views/comments/create.js.erb
$('#comments').append("<%= escape_javascript(render partial: '/comments/comment', locals: { comment: #comment } ) %>");
$('form.new_comment').find("input#comment_body").val('');
Also to note::
I'm using #new_comment so there is no interference when you render a newly created comment
You'll need to add #new_comment in 2 places, first in your posts show action and also in your comments create action

Rails ajax error while creating

Hello guys I want use ajax in my rails application :
Here is my routes.rb file
ExampleAjax::Application.routes.draw do
root 'users#index'
resources :users
end
my controller file
class UsersController < ApplicationController
def index
#users = User.all
#user = User.new
end
def create
#user = User.new(user_params)
respond_to do |format|
if #user.save
format.html { redirect_to #user, notice: 'User was successfully created.' }
format.js {}
format.json { render json: #user, status: :created, location: #user }
else
format.html { render action: "new" }
format.json { render json: #user.errors, status: :unprocessable_entity }
end
end
end
private
def user_params
params.require(:user).permit(:fname)
end
end
My view files
index.html.erb
<b>Users</b>
<ul id="users">
<% #users.each do |user| %>
<%= render user %>
<% end %>
</ul>
<br>
<%= form_for(#user, remote: true) do |f| %>
<%= f.label :fname %><br>
<%= f.text_field :fname %>
<%= f.submit %>
<% end %>
new.html.erb
<%=form_for(#user, remote: true) do |f|%>
<p>
<%= f.label :fname %><br>
<%= f.text_field :fname %>
</p>
<p>
<%= f.label :lname %><br>
<%= f.text_field :lname %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
_user.html.erb
<li><%= user.fname %></li>
_create.js.erb
$("<%= escape_javascript(render #user) %>").appendTo("#users");
And my problem is when I click create user
I got the following error in console
POST http://localhost:3000/users 500 (Internal Server Error)
Your code is hitting this block:
format.js {}
Which has nothing defined in it, so your app will try to do what it normally does, ie. render the view for the action you are in.
You are in a create action, and your format is js, so it will try to render create.js.erb.
You should rename your _create.js.erb to remove the underscore.
Ajax
I want use ajax in my rails application
To give you some info about Ajax, it's basically integrated in your application already:
Ajax is a group of interrelated web development techniques used on the
client-side to create asynchronous web applications
It's basically a way to send an asynchronous request to your web app (through javascript). Asynchronous essentially means you're sending requests out of scope of the typical HTTP "synchronous" request structure
HTTP works by responding to requests. Each click you perform is sending a request to your server, which responds with data. Synchronous requests are ones you perform in order, whereas asynchronous "ajax" ones are sent independently
Code
Your problem is you don't have a create.js.erb file:
respond_to do |format|
format.html #-> action.html.erb
format.js #-> action.js.erb
end
Unless you call some other methods in this block (such as render nothing), Rails will look for your action.js.erb file in your views directory
Rails
Rails handles all requests equally, and determines if it's an ajax request using the ActionDispatch::Http::MimeNegotiation class
This means you don't have to do anything "special" to use Ajax -- just send the requests to your routes, and handle them in the backend using respond_to do |format|

Rails - undefined method `project_path' in first line of form?

I think I am stumbling upon a rendering/redirection issue. In my rails application I have clients who can have many projects. When I update a project I use a nested form with the form_for method, passing it a client and project instance variable, respectively.
Here is my code:
routes.rb:
resources :clients do
resources :projects
end
projects_controller.rb
def edit
#client = Client.find(params[:client_id])
#project = Project.find(params[:id])
end
def update
#project = Project.find(params[:id])
respond_to do |format|
if #project.update_attributes(params[:project])
format.html { redirect_to client_project_path(#project.client, #project), notice: 'Project was successfully updated.' }
format.json { head :no_content }
else
format.html { render action: "edit" } # !!this seems to be the problem
format.json { render json: #project.errors, status: :unprocessable_entity }
end
end
end
views/projects/_form.html.erb:
<%= simple_form_for([#client, #project]) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :title %>
<%= f.input :start_on %>
<%= f.input :end_on %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
When I simply display the edit action, everything works fine. If I update the project with valid data, everything is fine, too. The problem occurs when I type in invalid or missing data into the form - then the "else part" of the update method is called, and the action "edit" should be rendered.
This indeed happens, but it seems to me that something is wrong either with the "edit" method or my form, because when I change render action: "edit" to redirect_to action: "edit", it does redirect me (of course without error messages so it is clearly not the desired solution, but I just wanted to test).
When "edit" is rendered, this is the error message I am getting:
undefined method `project_path'
which is only referring to the first line in my form.
What am I doing wrong here? Sorry for the long question and thanks for any help!
You need to load your #client variable in the update action. Think of it this way, if you hit the else, what did the edit provide to the view, because you need just that when you render instead of redirect. Being that your resources are nested, the form_for helper needs both the client and the project.

Resources