I want to print a simple message as an alert like after a user write his email click on the subscribe button.
Your email is saved, you'll be contacted for a beta very soon!
This is my view:
<form action="/welcome/subscribe" date-remote="true">
<div>
<div id="bottomm">
<input id="bottom" type="text" name="email" placeholder="email" />
</div>
<div>
<input type="submit" value="Ok" class="fit" />
</div>
<%= alert %>
</div>
</form>
This is the subscribe method in my controller :
def subscribe
#test = Test.new
#test.email = params['email']
#test.save
redirect_to root_url, notice: "Your email is saved, you'll be contacted for a beta very soon!"
end
But nothing is showing. I saw some people with the same issue as mine on stack but I tried the solutions but it didn't worked.
I tried to do these but none worked for me.
flash.keep
flash[:notice] = "..."
flash.now[:notice] = "..."
flash[:alert] = "..."
flash.now[:alert] = "..."
and redirecting after
Do you have a block either in application.html.erb or whatever your root view is to actually display the flash, like so:
<% if notice.present? %>
<p><%= notice %></p>
<% end %>
If not, that could be the problem.
Related
very new and need guidance, I am a very junior dev. Working on my first project: auth. project - that i've been working on for several months. but I am hitting a wall on how to pull my user.id from my User_controller and import or pull that data into my index.html.erb view.
plan is to have "user.id". render on the page with a label field dynamically. So, if a X user signs in, that "user_id" will show on this label form field by default to show X user is signed, and create some logic later to have my controller validate user and allow to prompt a new modal to change password, but when after user is login, and it routes to /dashboard view, For what ever reason, I can't get the user_id to show in my Label >user_id< using from bootstrap. I feel like this might be easy, but I'm not sure I am fully understand how rails can inject that data resource on the page dynamically
I have tried <%= #{:user_id}%>, change the label type id:/user_id with <%= #{:user_id}%>
this is what my user.controller looks like:
class UserController < ApplicationController
def index
# rendering json on page: user data
render json: User.all
end
def create
user = User.new(
first_name: params[:fname],
last_name: params[:lname],
username: params[:username],
password: params[:password],
password_confirmation: params[:password_confirmation]
)
if user.save
session[:user_id] = user.id
flash[:success] = "text"
#redirect_to '/login'
else
flash[:warning] = "text"
#redirect_to 'register'
end
end
def show
# render plain: params[:id]
#render json: userdata[:users].select {|user| user.get_id() == params[:id].to_i}
if User.exists?(params[:id])
render json: User.find(params[:id].to_i)
else
render plain: "that user doesnt exist: #{params[:id]}"
end
end
def validate
puts params
username = params[:username]
exists = User.exists?(username: username)
# puts exists
render json: {"exists": exists, "username": username}
end
end
and this is my html.erb
<% content_for :content do %>
<div class="container">
<div class="row">
<div class="col-12">
<h1 class=display-4>Welcome to your home page </h1>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-12">
<div class="jumbotron">
<p class="lead">needing to change your password - <strong class="text-success">reset your password easy</strong>.</p>
</div>
</div>
</div>
</div>
<div class="container">
<div class="row">
<div class="col-12">
<form class="row g-3">
<div class="col-auto">
<label for="username" class="visually-hidden">Example:user_id</label>
<input type="text" readonly class="form-control-plaintext" id="username" value="Helloguy123#">
</div>
<div class="col-auto">
<label for="password" class="visually-hidden">Password</label>
<input type="password" class="form-control" id="password" placeholder="Password">
</div>
<div class="col-auto">
<button type="submit" class="btn btn-primary mb-3">Confirm identity</button>
</div>
</form>
<% end %>
<%= render template: "layouts/application" %>
I have very simple HTML (password.html.erb):
<h1>Enter business password to enter:</h1>
<input type="text" id="password" name="enter password"/>
<input type="submit" method="post" name="Submit"/>
This should, on clicking of submit, trigger an action in my controller called 'check':
def check
#entered = params['password']
if #entered == current_customer.business.manager_password_digest
puts("success!")
redirect to '/manage'
else
flash[:danger] = 'Invalid password'
render 'password'
end
end
Here is my route:
get '/password' => 'pages#password'
post '/password' => 'pages#check'
But when I click submit, nothing happens. Is it not possible to use an input in this way?
You haven't told your button to execute which action on click. for this you should use action for the submit button.
<h1>Enter business password to enter:</h1>
<input type="text" id="password" name="enter password"/>
<input type="submit" method="post" name="Submit"/ action = '/password'>
You should be using rails helpers and you need to specify the path where you want to post the data:
<h1>Enter business password to enter:</h1>
<%= form_tag("/password") do %>
<%= text_field_tag :password %>
<%= submit_tag 'Submit' %>
<% end %>
I have a frontend rails app that is requesting a rails API. When my user wants to create an account, he is submitting the account form on the front-end app :
<h1>Create Account</h1>
<form action="http://localhost:3000/accounts" method="post">
<input name="authenticity_token" value="<%= form_authenticity_token %>" type="hidden">
<div class="form-group">
<%= label_tag 'account[name]', "name" %>
<input type="text" name="account[name]" required>
</div>
<div class="form-group">
<%= label_tag "account[contact_mail]", "E-Mail" %>
<input type="text" name= "account[contact_mail]" required>
</div>
<div class="form-group">
<%= label_tag "account[contact_tel]", "Telephone" %>
<input type="text" name= "account[contact_tel]" required>
</div>
<div class="form-group">
<%= label_tag "account[iban]", "Iban" %>
<input type="text" name= "account[iban]">
</div>
<div class="form-group">
<%= label_tag "account[bic]", "Bic" %>
<input type="text" name= "account[bic]">
</div>
<input type="submit">
<% if #errors %>
<ul class="list-unstyled">
<%#errors.each do |error|%>
<li class="has-error"><%=error%></li>
<% end -%>
</ul>
<% end -%>
</form>
On submit the method create from the front-end app account controller is called. The create method from the front-end app is then calling the create method on the rails API which is responsible for updating the database and rendering JSON to the front end app.
1) AccountController#create from the front-end app :
def create
# Post sur API create Account
#response = HTTParty.post(ENV['API_ADDRESS']+'api/v1/accounts',
:body => { :name => params[:account][:name],
:contact_mail => params[:account][:contact_mail],
:contact_tel => params[:account][:contact_tel],
:legal_status => params[:account][:legal_status],
:iban => params[:account][:iban],
:bic => params[:account][:bic]
}.to_json,
:headers => { 'X-User-Email' => session[:user_email], 'X-User-Token'=> session[:user_token], 'Content-Type' => 'application/json' } )
# Erreur Mauvais Auth Token
if #response["error"] == "You need to sign in or sign up before continuing."
redirect_to unauthorized_path
# erreur de validation
elsif #response["errors"]
#errors = #response["errors"]
flash[:alert] = "heello"
render :new
else
account_id = #response["account"]["id"]
redirect_to account_path(account_id)
end
end
2) AccountController#create from the API :
def create
#account = Account.new(account_params.merge(admin: current_user))
authorize #account
if #account.save
render :show
else
render_error
end
end
render error is a method that render errors in JSON format :
def render_error
render json: { errors: #account.errors.full_messages }, status: :unprocessable_entity
end
If there are validations errors when submitting the from to the API, I display them on the front end app next to the form :
<% if #errors %>
<ul class="list-unstyled">
<%#errors.each do |error|%>
<li class="has-error"><%=error%></li>
<% end -%>
</ul>
My problem is that I also wish to prepopulate the form with the data the user already submitted for better user experience.
I know there are already posts about how to prepopulate forms with rails in case of validation errors but I feel they did not really address my problem with this "double app pattern" and with my front-end app not having any models (all models / DB interactions are dealt in the API)
How can I prepopulate my form with the user's input after I receive an error from my JSON API ?
In the form you have, you could add value attributes to the input fields that populate with irb instance variables
<input type="text" name="account[name]" value="<%= #account_name %>" required>
Then in AccountController#create, set the instance variables based on the the params you received when you want to display the invalid data.
```
elsif #response["errors"]
#errors = #response["errors"]
#new code
#account_name = params[:account][:name]
#set each variable, extra to method or class for cleaner style
flash[:alert] = "heello"
render :new
```
When the form initially renders these variables will be uninitialize/nil so there will be no values in the form boxes, and then you can explicitly set them in the controller when the validation fails but you want to maintain data in the form.
This is definitely an overly-manual way to accomplish maintaining the form state, and I suggest if you want to reuse the pattern in your app you take a look at using form_for. This post might give you some insight into doing that with plain ruby objects instead of model objects. Is it possible to create form for simple class
I have a form with multiple buttons, I want one of the buttons to NOT validate the form, specifically required true text box. Here is the button. I do have simple_form gem.
<div class="col-md-2"> <%= f.submit 'Process Custom Amt', class: "btn btn- primary btn-md", name: 'new_order_with_irregular_pmt' %></div>
Thanks in advance
In your controller, instead of:
if #order.save
redirect_to #order
else
render "orders/new"
end
You could use:
if params[:new_order_with_irregular_pmt]
#order.save(validate: false)
redirect_to #order
else
if #order.save
redirect_to #order
else
render "orders/new"
end
end
I would have two different names for each button in the form.
<input type="submit" name="validate" value="Submit" />
<input type="submit" name="dont_validate" value="Submit" />
then I would check in the controller which one was submitted
if params[:dont_validate]
#order.save(validate: false)
else
#order.save
end
In rails 4 a page is not showing an instance variable.
I have a form that triggers a post gives a flash message and redirects.
But the values are there and it never shows, any ideas?
slim Form
- unless #flash == nil
= #flash
= form_tag '/contact' do
= email_field_tag('email', nil, id:"email")
input.btn-submit name="submit" type="submit" value="Submit"
Controller
def form_posts_here
if UserMailer.zemail(params[:email]).deliver
flash[:success] = "Thank you!"
end
redirect_to contact_path
end
def new
#flash = flash[:success]
end
Seems like you don't have a way to show the flash messages.
Create a partial _flash.html.erb in your layouts folder and add this block of codes.
<% flash.each do |message_type, message| %>
<div class="alert alert-<%= message_type %> alert-dismissible" role="alert" id="flash">
<button type="button" class="close" data-dismiss="alert" aria-label="Close"><span aria-hidden="true">×</span></button>
<%= simple_format(message) %></div>
<% end %>
You can access this by adding <%= render 'layouts/flash' %> in your application.html.erb.
controller:
def new
flash[:success] = "Message goes here"
end
view:
- if flash[:success].present?
= flash[:success]