Displaying a messaging right away to the user when page is loaded - ruby-on-rails

I am not sure if this is possible but I want to display a flash message to the user when they come onto on of the pages automatically. I kind of played around with it but no luck. Does anyone know how to do that if so any help would be greatly appreciated!
CODE FOR CONTROLLER
class BookinController < ApplicationController
def flash
flash.now[:notice] = "Test"
render :action => :new
end
def bookin
#alert = "Successfully saved!"
end
def bookout
#customer_list = Customer.all
#customer_name = params[:customer_name_in]
#r = Customer.find_by_last(#customer_name)
end
end
CODE FOR VIEW
<h2>The Maintenance Functions are restricted to authorized users.
Please login below</h2>
<%= form_tag(bookin_bookout_path, :method => "post") do %>
<div class="field">
Name
<%= text_field_tag :customer_name_in %>
</div>
<br>
Password
<%= text_field_tag :customer_name_in %>
</div>
<br>
<div class="actions">
<br>
<%= submit_tag "Submit Customer Name" %>
</div>
<% end %>
<h2> Main Menu</td> </h2>

You could try the bootbox-rails gem.
In a nutshell:
Add it to your Gemfile,
Add it to your app/assets/javascripts/applications.js
Put something like this in your view:
<script>
<%= raw #alerts %>
</script>
Put something like this in your controller:
#alerts = "bootbox.alert('Some kind of alert!');"

Flash
You'll want to set the flash message in the action, so it's there when the user hits the page
The flash is basically a session variable which will only persist per one action, meaning if you set it on your action, the next one will not have the same message
You can set the flash, as you've already done, like this:
def action
flash[:notice] = "Welcome to our website"
end
Code
As RSB has queried, you've not provided us with the most specific code. So instead, I'll show you a simple example and look out for some comments to come back with updates:
#app/controllers/bookin_controller.rb
class BookinController < ApplicationController
def index
flash[:notice] = "Welcome To Our Page!"
end
end
#app/views/bookin/index.html.erb
<%= flash[:notice] %>
This will display your message for the rendered action. You don't need any specific methods - just set the flash var value in the action you're rendering

Related

Rails: render not updating page, but it's being returning in response

When calling render The view is not being updated, however, I do notice in the network tab, after the POST request is made to me POST route, it's returning HTML as the response, and the response has my rendered error message. It's just not updating the page. I don't know what to make of that.
In my POST action, I'm forcing this to be called
flash.now[:notice] = responseMessage
render :deactivate_show
Which renders the action:
def deactivate_show
#user = User.find(params[:id])
authorize! :deactivate_user, #user
if current_user.role == "admin"
if #user.broker?
#companyUsers = User.where(parent_id: #user.id)
#properties = Property.where(user_id: #user.id)
.or(Property.where(user_id: #companyUsers.ids))
elsif #user.broker_manager?
# get all agents in company
# exclude current user
# get broker
#companyUsers = User.where(parent_id: #user.parent_id)
.where.not(id: #user.id)
.or(User.where(id: #user.parent_id))
#properties = Property.where(user_id: #companyUsers.ids)
.or(Property.where(user_id: #user.parent_id))
else #user.agent?
#properties = #user.properties
if #user.parent_id?
#companyUsers = User.where(parent_id: #user.parent_id)
.where.not(id: #user.id)
.or(User.where(id: #user.parent_id) )
else
# dealing with owner.
#companyUsers = User.where('role IN (2,4,1)')
.where.not(id: #user.id)
end
end
else
end
end
which renders a view I have that displays the form.
I added to my show view:
<div class="messages">
<% flash.each do |key, value| %>
<div class="hello"><%= value %></div>
<% end %>
</div>
Note the class of "hello".
When I make a POST request, the response in the network tab has the notice:
Rendered from POST request response:
<div class="messages">
<div class="hello">testing errors</div>
</div>
Edit: here's the form:
<div class="form-wrap">
<%= form_with do %>
<%= button_tag( id: 'button--submit', class: 'button button--secondary') do %>
<i class="icon-arrow-right"></i>
<span>Deactivate</span>
<% end %>
<% end %>
</div>
Well the actual answer was something no one could have provided since I didn't share my form. I was using form_with, which apparently does AJAX by default, thus not rendering the view.
Thanks for the help from this question: Rails render not showing in browser, despite positive server reply
I've changed
<%= form_with do %>
to
<%= form_with local: true do %>
and now it works.
The Flash is only rendered upon a new request, which you don't make with render. Instead, you should use flash.now[:notice] to have it display on render.

Interpolating data in a rails view

I'm a beginner at rails and thus far interplating data in views has been pretty straight forward. I've been introduced to something slightly new as far as how the controllers are setup and as a result I'm not sure how one would go about getting the data to present in the view.
First controller
class PagesController < ApplicationController
def index
#guestbook_entry = GuestbookEntry.new
render "welcome"
end
end
Second controller
class GuestbookEntriesController < ApplicationController
def create
GuestbookEntry.create(guestbook_entry_params)
redirect_to root_path, notice: "Thank you for your entry."
end
private
def guestbook_entry_params
params.require(:guestbook_entry).permit(:body)
end
end
And here is the welcome.html.erb
<h1>Welcome to My Guestbook</h1>
<br>
<%= image_tag("under_construction.gif") %>
<div id="guestbook-entries">
<p>Guestbook Entries:</p>
<ul>
</ul>
</div>
<%= form_for #guestbook_entry do |f| %>
<%= f.label :body, "Guestbook Entry:" %>
<%= f.text_area :body %>
<%= f.submit "Submit" %>
<% end %>
So it wants me to iterate through all the entries and display them on a welcome page that's located in view/pages/welcome.html.erb.
Up to this point I guess I've only been doing basic simple rails applications where the view corresponded with the controller, and followed the typical CRUD setup, where index would hold the #xxx = Xxxx.all and new/create would handle #xxx = Xxxx.new/create/build. I thought I could simply move the PageController's index action to create/new and do
def index
#guestbook_entry = GuestbookEntry.all
render "welcome"
end
To satisfy the test (it looks for render welcome in the index action)
This seems weird but again I admit, I'm a beginner.
If you want to list all the guest book entries on your root page you would do something like:
class PagesController < ApplicationController
def index
#guestbook_entry = GuestbookEntry.new
#guestbook_entries = GuestbookEntry.limit(10).all
render "welcome"
end
end
And in your view you would list them like:
<% if #guestbook_entries.any? %>
<div id="guestbook-entries">
<p>Guestbook Entries:</p>
<% #guestbook_entries.each do |entry| %>
<ul>
<li class="entry"><%= h(entry.body) %></li>
</ul>
<% end %>
</div>
<% end %>
The rest of you application is correct - you should be creating entries in GuestbookEntriesController#create. In many real life applications then the functionality of the standard new and edit actions can actually be a totally different controller.

Rails: Why isn't the 'create' action saving the newly created Quiz instance?

My form gets passed a 'new' Quiz (not saved to the database). My form partial looks like this:
<%= form_for(#quiz) do |f| %>
<p>
<%= f.check_box(:answer1) %>
<%= f.check_box(:answer2) %>
<%= f.check_box(:answer3) %>
<%= f.check_box(:answer4) %>
<%= f.check_box(:answer5) %>
<%= f.check_box(:answer6) %>
<%= f.check_box(:answer7) %>
<%= f.check_box(:answer8) %>
</p>
<p>
<%= f.submit("Get my results!") %>
</p>
<% end %>
Here is my QuizzesController#create action:
def create
#results = Quiz.create(post_params) #from private method
if #results.save
redirect_to results_path
else
#error handle here
end
end
...which gets triggered when the user clicks 'get my results' on my quiz form. And the post_params method looks like this:
def post_params
params.require(:quiz).permit(:id, :user_id, :answer1, :answer2, :answer3, :answer4, :answer5, :answer6, :answer7, :answer8) #add other attributes here
end
My results/index.html.erb looks like this:
<div class="container">
<!-- Example row of columns -->
<div class="row">
<h1>Results</h1>
<p><%= #results.inspect %></p>
</div>
</div>
But that 'inspected' Quiz instance returns 'nil' for all the answers1, answers2 etc attributes. Any idea why that would be? Is there something I'm NOT doing to save the user's answers to the database?
The reason it shows nil is because you are not setting the variable.
After creating and saving, you redirect to results_path and the variable #results does not persist during a redirect. Without seeing the full code, I'll have to guess at your naming conventions but there are two ways to do this.
1) If you want to redirect to the index then in the code for your index action, you can set the variable:
#results = Quiz.last
This is easy to work with in development because you are the only user and this will always return the last quiz you created. Not so great in production.
2) The alternative is to redirect to the show action for that quiz.
def create
#results = Quiz.new(post_params)
if #results.save
redirect_to result_path(#results)
else
# error handle here
end
end
Again, I have had to guess that result_path is the correct path. Without seeing the full routes file, I cannot be sure but you can rename accordingly if necessary.

Adding a user_id to a Message model

I currently have a simple app that includes user authentication through devise and a message model(the message model uses Jquery and Faye). Both are working fine independently, but I would like to add a user_id to the messages.
I have already updated the schema and models with the relationship, but I am having trouble inputting the necessary code to have the view and controller input the relationship into the db, while keeping the jquery working. I wasn't sure of the best way, but here I tried to create a hidden field that would pull the user_id, not sure if this is even possible. Here is the applicable code, any help is appreciated.
Message index.html.erb
<ul id="chat">
<%= render #messages %>
</ul>
<%= form_for Message.new, :remote => true do |f| %>
<div class="field">
<%= f.text_field :content %>
</div>
<div class="field">
<%= f.hidden_field :user_id %>
</div>
<div class="actions">
<%= f.submit "Send" %>
</div>
<% end %>
create.js.erb for messages
<% broadcast "/messages" do %>
$("#chat").append("<%= escape_javascript render(#user.message) %>");
<% end %>
$("#new_message")[0].reset();
Messages Controller
class MessagesController < ApplicationController
def index
if #authentications = current_user
#messages = Message.all
else
redirect_to authentications_url
flash[:notice] = "You need to sign in before answering questions"
end
end
def create
#user = User.find(params[:user_id])
#message = #user.message.create(params[:message])
end
end
I think you have everything you would need, but if not, let me know and I will be happy to provide it for you.
Thanks, everyone.
two things to correct,
1)use user association to create message instance in form(probably current_user if logged-in user create a message)
<%= form_for user.messages.new, :remote => true do |f| %> #// assuming its has many association
2) if it is has_many association then change association in create action
#message = #user.messages.create(params[:message])

How do I display "wall posts" on a user's page?

I'm trying to show "wall posts" that all users have made on a specific user's page, but I'm having difficulty showing the correct posts.
Users controller:
def show
#user = User.find_by_cached_slug(params[:id])
#posts = Post.find_all_by_poster(params[#user.id])
if signed_in?
#post = Post.new
end
respond_to do |format|
format.html # show.html.erb
format.xml { render :xml => #user }
end
end
Post form:
<%= form_for #post do |f| %>
<div class="field">
<%= f.text_area :content %>
</div>
<div class="field">
<%= f.hidden_field :user_id, :value => current_user.id %>
</div>
<div class="field">
<%= f.hidden_field :poster, :value => #user.id %.
</div>
<div class="actions">
<%= f.submit "Submit" %>
</div>
<% end %>
When a user creates a post the current_user id is saved in the posts table as the :user_id and the user id of the user's page they're posting on is saved as :poster. This part is working, but I don't understand how to render #posts so that only the posts that have been made on that user's page appear.
The approach I'm trying is somehow showing/filtering? all posts where :poster matches the user id of the user's page; however, I don't know how to make this work or if there is a better way. Any help?
Note: I'm using the slugged gem. In the Users/show view, I use <%= render #posts %>. Eventually, I'd like for users to be able to comment on posts, if that affects any design decisions.
Thanks very much for your help! Please let me know if any more information is needed.
I think this line is the issue:
#posts = Post.find_all_by_poster(params[#user.id])
#user is the the record for the user who wall is now being viewed. (right?) You need all the posts that were posted to that users wall that is all the Post records where poster == #user.id. There is no need to look in the params hash for this. I believe that this line should instead be:
#posts = Post.find_all_by_poster(#user.id)
If this is incorrect, it means that I am not clear how your show action is meant to work. There are two different things that could be #user. By convention this should always refer to the record of the person at the other end of the connection. In your case, it looks like it instead refers to the person whose wall is being viewed. Is that correct?

Resources