how to update user in ruby on rails - ruby-on-rails

I am trying to update user info and i am having error that it didn't get any data from my form
Here is my user.controller:
def update
if !session[:id]
redirect_to '/users'
else
#user = User.find(params[:id])
#user.update(update_params)
if #user.valid?
#user.save
redirect_to '/events'
else
flash[:errors] = #user.errors.full_messages
redirect_to "/users/#{#user.id}/edit"
end
end
end
def update_params
params.require(:user).permit(:fname, :lname, :email, :city, :state)
end
edit update form
here is my edit.html.erb form:
<form action="/users/<%= #user.id %>/update" method="post">
<input type="hidden" name="_method" value="patch">
<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
<div class="form-group row">
<label for="fname" class="col-sm-2 col-form-label">First Name</label>
<div class="col-sm-10">
<input type="text" name="user[fname]" class="form-control" placeholder="<%= #user.fname %>">
</div>
</div>
<div class="form-group row">
<label for="lname" class="col-sm-2 col-form-label">Last Name</label>
<div class="col-sm-10">
<input type="text" name="user[lname]" class="form-control" placeholder="<%= #user.lname %>">
</div>
</div>
<div class="form-group row">
<label for="email" class="col-sm-2 col-form-label">Email</label>
<div class="col-sm-10">
<input type="email" name="user[email]" class="form-control" placeholder="<%= #user.email %>">
</div>
</div>
<div class="form-group row">
<label for="location" class="col-sm-2 col-form-label">Location</label>
<div class="col-sm-5">
<input type="text" name="user[city]" class="form-control" placeholder="<%= #user.city %>">
</div>
<div class="col-sm-5">
<select class="custom-select" name="user[state]">
<%= options_for_select(us_states)%>
</select>
</div>
</div>
<div class="form-group row clearfix">
<div class="col-sm-10 offset-sm-2">
<button type="submit" class="btn btn-primary float-right">Update</button>
</div>
</div>
</form>
Just updated my html form
this is error in terminal when i hit submit from my form:
(0.1ms) begin transaction User Exists (1.7ms) SELECT 1 AS one
FROM "users" WHERE ("users"."email" = 'nhan13574#gmail.com' AND
"users"."id" != 1) LIMIT 1 (0.1ms) rollback transaction Redirected
to http://localhost:4000/users/1/edit

Can you share the form? mostly the issue is there.
Also, #user.update actually saves the data in db, no need to save after it.. here is a refactored version of your snippet:
def update
return redirect_to '/users' unless session[:id]
#user = User.find(params[:id])
if #user.update(update_params)
redirect_to '/events'
else
flash[:errors] = #user.errors.full_messages
redirect_to "/users/#{#user.id}/edit"
end
end

Related

Trying to render value of input field

Trying to work with a input value present in the source code only when the user has tried to login once (and entered a wrong password).
The scenario is as follows:
First attempt before login, part of the code looks like this:
<div class="form-group">
<label class="control-label col-md-4" for="user_email">Email</label>
<div class="col-md-8">
<input class="text-field form-control" html="{:spellcheck=>"false"}" id="user_email" name="user[email]" type="email" value="" />
</div>
</div>
After a second attempt happens, the email address that was used it's rendered in value:
<div class="form-group">
<label class="control-label col-md-4" for="user_email">Email</label>
<div class="col-md-8">
<input class="text-field form-control" html="{:spellcheck=>"false"}" id="user_email" name="user[email]" type="email" value="heregoestheemail#gmail.com" />
</div>
</div>
How can I render that email address if the user is not logged in yet? I know that once logged I'd do something like <%= current_user.email %> but there is way to get that value attribute?
you should work with form_for
<%= form_for #user do |f| %>
<% f.text_field :email (not sure f.email_field works)
<%= end %>
be sure #user is define in controller (#user = User.new or #user is come back from controller with errors => show #user.errors and contain precedent values)
http://guides.rubyonrails.org/form_helpers.html

Unauthorize error on password update Devise

I'm working on a rails api and using devise_token_auth for the authentication, when I try to update password by hitting the /auth/password with put request it responsds with error 401 i.e. unauthorized. My server logs show me this
Started PUT "/auth/password" Processing by
DeviseTokenAuth::PasswordsController#update as HTML Parameters:
{"password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}
Can't verify CSRF token authenticity Completed 401 Unauthorized in
routes.rb
mount_devise_token_auth_for 'User', at: 'auth' ,:controllers => { :omniauth_callbacks => 'omniauth' }
view.html (angularjs)
<div class="container">
<div class="row">
<div class="row">
<div class="col-xs-6 col-xs-offset-3 que">
<img src="./uploads/img/web-logo.png" class="img-responsive" alt="Logo">
</div>
</div>
<div class="col-xs-12 reset-pas">
<form name="update_pass" ng-submit="updatePassword_controller()" role="form" class="lost_reset_password">
<p class="error_msg" ng-show="update_pass.password_confirmation.$error.passwordVerify">
Passwords are not equal!
</p>
<label>New password</label>
<input type="password" name="password" ng-minlength="8" ng-model="updatePasswordForm.password" required="required" class="form-control">
<span>Minimum 8 Charachters</span>
<br>
<label>Re-enter new password</label>
<input type="password" name="password_confirmation" ng-minlength="8" ng-model="updatePasswordForm.password_confirmation" required="required" class="form-control" password-verify="updatePasswordForm.password" >
<button type="submit" class="btn btn-default" id="reset-submit">Save</button>
</form>
</div>
</div>
</div>
controller.js
$scope.updatePassword_controller = function() {
$auth.updatePassword($scope.updatePasswordForm)
.then(function(resp) {
console.log(resp)
$location.path('/')
})
.catch(function(resp) {
console.log(resp)
});
};
Update
Note
I'm facing this issue only for password update
Update
I installed gem 'angular_rails_csrf' Now it's giving only the authorization error not the csrf attack error
Use the Rails form_tag or form_for helpers. They add will add a hidden field for the XCSRF token:
<div class="container">
<div class="row">
<div class="row">
<div class="col-xs-6 col-xs-offset-3 que">
<img src="./uploads/img/web-logo.png" class="img-responsive" alt="Logo">
</div>
</div>
<div class="col-xs-12 reset-pas">
<%= form_tag "#", { "ng-submit" => "updatePassword_controller()", "role" => "form", "class" => "lost_reset_password"} do %>
<p class="error_msg" ng-show="update_pass.password_confirmation.$error.passwordVerify">
Passwords are not equal!
</p>
<label>New password</label>
<input type="password" name="password" ng-minlength="8" ng-model="updatePasswordForm.password" required="required" class="form-control">
<span>Minimum 8 Charachters</span>
<br>
<label>Re-enter new password</label>
<input type="password" name="password_confirmation" ng-minlength="8" ng-model="updatePasswordForm.password_confirmation" required="required" class="form-control" password-verify="updatePasswordForm.password" >
<button type="submit" class="btn btn-default" id="reset-submit">Save</button>
</form>
</div>
</div>
</div>
I simply made a condition in applicationcontroller.rb like below and it worked out . The main idea is simply to override the functionality of Devise
if params[:controller] == "devise_token_auth/passwords" && params[:action] == "update"
uri = URI.parse(request.headers.env['HTTP_REFERER'])
query_params = CGI.parse(uri.query)
email = query_params['uid'].first
user = User.find_by_email(email)
user.password = params[:password]
user.password_confirmation = params[:password_confirmation]
if user.save
render json: {message: 'Password Updated successfully', status: 200}
else
render json: {message: 'Password Could not changed , Please contact to support Team', status: 401}
end
end
Although it's not the proper solution but i couldn't think of anyother one . So please bear with me .In it we're fetching email from url

I have a customized form but whatever written on the form is not saved in database

I have a form that uses styles of twitter/bootstrap
however the content of the form is not saved.
May I please know what am I missing?
<%= form_for #customer_detail, url: { action: "create" } do |f| %>
<div class="form-group">
<div class="row">
<div class='col-sm-3'>
<label for="Check in">Check in:</label><br>
<div class='input-group date' id='datetimepicker1'>
<input class="form-control" type='text'>
<span class="input-group-addon"><span class=
"glyphicon glyphicon-calendar"></span></span>
</div>
</div><label for="Check out">Check out:</label><br>
<div class='col-sm-3'>
<div class='input-group date' id='datetimepicker2'>
<input class="form-control" type='text'>
<span class="input-group-addon"><span class=
"glyphicon glyphicon-calendar"></span></span>
</div>
</div>
</div>
<% end %>
Seems like you should read this article. It describe to create form use Rails helpers and action for save to database.

Stripe different plans

So I got stripe up and running, however I have 3 different payment plans.
I'd like to capture what plan they clicked on, and use that to connect them to their right plan id.
This is what my form looks like:
<%= form_tag charges_path, id: "payment-form" do %>
<span class="payment-errors"></span>
<div class="form-row">
<label>
<span>Card Number</span>
<input type="text" size="20" data-stripe="number" maxlength="20" />
</label>
</div>
<div class="form-row">
<label>
<span>CVC</span>
<input type="text" size="4" data-stripe="cvc" maxlength="4"/>
</label>
</div>
<div class="form-row">
<label>
<span>Expiration (MM/YYYY)</span>
<input type="text" size="2" data-stripe="exp-month" maxlength="2"/>
</label>
<span> / </span>
<input type="text" size="4" data-stripe="exp-year" maxlength="4"/>
</div>
<button type="submit">Submit Payment</button>
<% end %>
I link to them like this:
<%= link_to 'Start Your Free Trial', new_charge_path(:plan_id => 1) %>
and the controller looks like this:
def create
customer = Stripe::Customer.create(
:email => 'exaimple#stripe.com',
:plan => plan_id,
:card => params[:stripeToken]
)
current_user.update_attributes(:stripe_customer_token => customer.id)
redirect_to root_url, notice: 'Successfully subscribed'
rescue Stripe::CardError => e
flash[:error] = e.message
redirect_to charges_path
end
which results in the error:
undefined local variable or method `plan_id'

Nested form accepts_nested_attributes_for giving dynamic Array - Rails4

I am working on Rails4 with Nested form, accepts_nested_attributes_for i can able to generate the nested form but its giving dynamic array the the form when i inspect the form.
<input type="text" name="event_venue[event_contact_details_attributes][1403763304978][name]" id="event_venue_event_contact_details_attributes_1403763304978_name" class="form-control">
But it should be,
<input type="text" name="event_venue[event_contact_details_attributes][1][name]" id="event_venue_event_contact_details_attributes_1_name" class="form-control">
<div class="formWrapper">
<div class="col-md-6">
<div class="form-group">
<label for="exampleInputEmail1">Name</label>
<input type="text" name="event_venue[event_contact_details_attributes][1403764358820][name]" id="event_venue_event_contact_details_attributes_1403764358820_name" class="form-control">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Phone</label>
<input type="text" name="event_venue[event_contact_details_attributes][1403764358820][telephone]" id="event_venue_event_contact_details_attributes_1403764358820_telephone" class="form-control">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email</label>
<input type="text" name="event_venue[event_contact_details_attributes][1403764358820][email]" id="event_venue_event_contact_details_attributes_1403764358820_email" class="form-control">
</div>
<div class="clearfix"></div>
<input type="hidden" value="false" name="event_venue[event_contact_details_attributes][1403764358820][_destroy]" id="event_venue_event_contact_details_attributes_1403764358820__destroy"><a onclick="remove_fields(this); return false;" href="#">remove</a>
</div>
</div>
Can you help me out where i am missing the things...!!!
In first nested form set it's coming right,
<div class="formWrapper">
<div class="col-md-6">
<div class="form-group">
<label for="exampleInputEmail1">Name</label>
<input type="text" value="AS" name="event_venue[event_contact_details_attributes][0][name]" id="event_venue_event_contact_details_attributes_0_name" class="form-control">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Phone</label>
<input type="text" value="AS" name="event_venue[event_contact_details_attributes][0][telephone]" id="event_venue_event_contact_details_attributes_0_telephone" class="form-control">
</div>
<div class="form-group">
<label for="exampleInputEmail1">Email</label>
<input type="text" value="AS" name="event_venue[event_contact_details_attributes][0][email]" id="event_venue_event_contact_details_attributes_0_email" class="form-control">
</div>
<div class="clearfix"></div>
<input type="hidden" value="false" name="event_venue[event_contact_details_attributes][0][_destroy]" id="event_venue_event_contact_details_attributes_0__destroy"><a onclick="remove_fields(this); return false;" href="#">remove</a>
</div>
</div>
Event Venue Model,
has_many :event_contact_details, :dependent => :destroy
accepts_nested_attributes_for :event_contact_details, allow_destroy: true
Controller,
def new
#event_venue = EventVenue.new
#event_venue.event_contact_details.build
end
form,
<%= f.fields_for :event_contact_details do |builder| %>
<%= render :partial => 'event_venues/event_contact_detail_fields',
:locals => { :f => builder } %>
<% end %>
<p><%= link_to_add_fields "Add More", f, :event_contact_details %></p>

Resources