Rails 4 Close current tab from controller - ruby

So, I have this html.erb and this controller (shown below). What I want is to, if simple_captcha.valid? to increment reports, save, AND close current tab. I want to do it from controller, if possible! (And also, would it be a good practice?)
I saw several examples of this done on view page using javascript, but I know nothing of javascript and, if possible, I'd like to deal with it on controller. But, in case I really have to learn javascript to achieve what I want, which direction should I take?
#view (html.erb)
<h4>To report, complete captcha</h4>
<%= show_simple_captcha %>
<%= button_to "report post", create_report_post_path(#forum_post.id) %>
-----------------------------------
#controller
def new_report_post
#forum_post = ForumPost.find(params[:id])
end
def create_report_post
#forum_post = ForumPost.find(params[:id])
if simple_captcha_valid?
#forum_post.reports += 1
#forum_post.save
redirect_to ???
flash[:success] = "Mandou ver."
else
redirect_to report_post_path
flash[:warning] = "Captcha inválido."
end
end

I don't think, you can close a tab, unless that tab was explicitly opened by javascript.
You can refer to this question: link
If however, you are opening the view using javascript. you can send window.close() using a js.erb view.
Instead of redirect_to, it would be something like
respond_to do |format|
format.js { render "js_erb_view" }
end
Inside your js.erb view file,you can send
window.close()
This would only work if you send an ajax request. One of the possible solutions to make this work :)

Related

How to implement link_to, AJAX, remote: true, respond_to without rendering new url Rails 6

I'm trying to implement adding upvote and downvotes to an app, submit the controller actions remotely using a button or link_to, and refresh a count section with AJAX.
Somehow upvoting or downvoting always redirects to a path of a member. When I use head :no_content, I can't submit the form aka link_to. Having some respond_to do | f |... also just renders the action URL.
Thus, remote: true is kind of not working, as I have another controller using <%= form_for([entry, entry.review], remote: true, :authenticity_token => true) do |f| %> and it works perfectly.
I have tried implementing here, here, here, and this tutorial and this but nothing seems to work.
I'm using the acts_as_votable. Everything works except the routing functionality with AJAX
# routes.rb
resources :entries do
member do
post 'upvote'
post 'unupvote'
post 'downvote'
post 'undownvote'
end
end
# entries_controller.rb
def upvote
#entry.liked_by current_user
end
def unupvote
#entry.unliked_by current_user
end
def downvote
#entry.disliked_by current_user
end
def undownvote
#entry.undisliked_by current_user
end
# entries/index.html.erb
...
<%= button_to upvote_entry_path(entry.id), remote: true,
class: "btn",
id: "upvote-button-#{ entry.id }" do %>
<i class="bi bi-hand-thumbs-up" style="color: #ababab;" id="upvote-<%= entry.id %>"></i>
<small id="upcount-<%= entry.id %>" >
<%= render 'entries/upvote', entry: entry %>
</small>
<% end %>
...
# entries/_upvote.html.erb
<%= entry.get_upvotes.size %>
# entries/upvote.js.erb
$('#upvote-<%= entry.id %>').className('bi bi-hand-thumbs-up-fill');
$('#upvote-<%= entry.id %>').attr('href', '/entries/<%= entry.id %>/unupvote');
$('#upcount-<%= entry.id %>').html('<%=j render 'entries/upvote', entry: entry %>');
Edit, I have changed my link_to to button_to, changed the routes to post
Not sure if your a tag is inside other elements but you might want to consider using a button_to instead of a link_to.
So far the temporary solution, not probably recommended but still does the job programming practice, is hiding and unhiding certain elements on specific conditions.
Upon user interaction (e.g onClick), unhide and hide elements while updating values that resemble the controller update. Simply simulate a refresh and update the form paths/controller actions they point to.
This will mostly work better with boolean check-box forms, likes or dislikes where variables will only alternate between two instances at max. Hence you don't have to write much javascript to handle pseudo outputs.
But still, I'm sure there's a better method for example WebSockets through Action Cable. That can probably be overkill but the closest to realtime updates. respond_to just doesn't seem to work

Rails email preview for users in production

Context
Gems like mail_view, mailcatcher, rails_email_preview, etc. seem to be more developer-oriented (a way to debug a template). But I need something that will be used by the trusted users of my rails app in production.
My app is a project management app, where project managers can update the status of their projects, operations during which emails must be sent to project contractors, developers, clients, etc.
The project manager must be able to tell whether or not he wants to send an email (this is easy), and be able to customize to some extent the message content (not the design, only specific text parts should be enough). They DO want to have some control over the email about to be sent, ie, they need a preview of the email they customized. Why ?
Project Managers are trusted users/programmers, and I let them add HTML as custom parts of the email (We are talking about a small-scale app, and the project managers are all trusted employees). But a closing tag is easily forgotten, so I want to provide them with a mean to check that nothing is wrong. Eg. that the text does not all appear as <h2> just because they forgot a closing </h2>
Some email templates already include some info about what the PM is writing about, and the PM may not be aware of it (understand : may be too drunk to remember it). An email preview is just a way to avoid duplicate sentences (like two times Hello M. President,)
CSS styles are applied to the email. It can be hard to anticipate the effect of tags like <h2>, etc. So I need to render the email with the CSS
REMARKS
Previsualize & Send button
Project managers have access to a form that will feed the content to my Rails app. I am thinking on having both a normal submit button, and a previsualize button. I will probably use some tricks given by this SO question to differentiate the behaviours of the 2 buttons
Letter_opener : a nice gem, but exclusive ?
I am using letter_opener for debug (so different context), but this is typically the preview I'd like to show to the project manager. However, in order to be used, letter_opener requires to modify action_mailer configuration config.action_mailer.delivery_method = :sendmail # (or :letter_opener). So I can only previews emails, or send them for real, not both ? I would accept a solution that would let me choose whether to use letter_opener or send the email for real
Small Editor ?
Instead of blindly trusting my project managers' ability to write basic html without forgetting closing tag, maybe you could recommend a nice WYSIWYG editor that would show the content of my f.text_area() ?
This would be a bonus, not an actual answer to my question
Email rendering engine ?
I am now aware that different email clients can render the email client differently. I will ignore this for now. So the way the preview is rendered doesn't matter. I like the rendering of letter_opener however
Current Code
View > Controller > Mailer
my_email_view.html.erb
<%= form_tag some_mailing_list_path %>
<%= fields_for :email do |f| %>
<!-- f.text_field(:subject, ....), etc -->
<% end %>
<%= submit_tag("Send email") %>
<%= submit_tag("Preview") %>
<% end %>
my_controller.rb
before_action :prep_email # Strong parameters, define #mail with form contents
# Handles the POST
def some_action
check(:to, :from, :subject) # I check the parameters in private functions
if email_alright? # Above checks will raise a flag if something went wrong
if Rails.env.production?
MailingListsMailer.my_action(#mail).deliver_later
else
MailingListsMailer.my_action(#mail).deliver_now
end
flash.notice = "Email sent"
redirect_to :back
else
redirect_to :back
end
end
mailing_list_mailer.rb
def my_action(message)
format_mail_params(message) # Will set more variables
#etude = etude
#include_reference = message[:include_reference]
#include_description = message[:include_description]
dst = Proc.new { read_emails_file }
mail(
to: dst,
from: message[:from],
subject: #subject_full)
end
Question update: based on your pseudocode, this is a simple case of creating a status update model and emailing the update to a mailing list.
There are several ways you can go about it, but I'd suggest that you keep things simple and avoid using gems.
<%= link_to "New update", new_status_update_path, class: 'button' %>
Model
class StatusUpdate
belongs_to :sender, class_name: 'User'
belongs_to :mailing_list
end
Controller
class StatusUpdateController
def new
#status_update = StatusUpdate.new
end
def create
#status_update = StatusUpdate.create(status_update_params)
#status_update.mailing_list = MailingList.where(whichever_mailing_list)
if #status_update.save
redirect_to :action => "preview", :status_update => #status_update
end
end
def preview
#status_update = StatusUpdate.where(id: params[:id]).first
#mailing_list = MailingList.where(id: #status_update.mailing_list_id)
end
def send
#status_update = StatusUpdate.where(id:params[:status_update_id]).first
Mailer.status_update_email(#status_update).deliver
end
end
status_updates/new.html.erb
<%= simple_form_for(#status_update) do |f| %>
<%= f.input :title %>
<%= f.input :content, as: :text %>
<%= f.button :submit, 'Post update' %>
<% end %>
status_updates/preview.html.erb
<h1>Preview</h1>
<%= simple_form_for(#status_update, :url => url_for(:controller => 'StatusUpdateController, :action => 'send') do |f| %>
<%= f.input :subject %>
<div class="email-render-container">
<%= #status_update.content %>
</div>
<p>Make changes</p>
<%= f.input :content, as: :text %>
<%= f.button :submit, 'Approve and send emails' %>
<% end %>
If I were you, I'd do away with the preview feature. If you're
loading content from a template and all you're worried about are
potential duplicate content, just do this:
Controller
class StatusUpdateController
def new
#status_update = StatusUpdate.new
template = UpdateTemplate.where(however_you_assign_the_template)
#status_update.content = template.content
end
def create
#status_update = StatusUpdate.create(status_update_params)
#status_update.mailing_list = MailingList.where(whichever_mailing_list)
if #status_update.save
Mailer.status_update_email(#status_update).deliver
end
end
end
and style the new status update form with css to simulate writing on the actual email template. You'll save your users and yourself a lot of time.
wysiwyg editor
Never trust the end user with the ability to write html. Depending on your needs, I find https://www.froala.com/wysiwyg-editor easy to deploy.
differentiating buttons
Just use a preview icon with a label on your button and/or a subtitle under your button to differentiate your buttons. You don't need much command logic in your view.
Alternatively, if you think that the preview is important to your end users, just use the "preview" button as the next logical step instead of presenting your users with too many unnecessary choices.
Suggestions
Adopting a front end framework like Angularjs makes this sort of use case almost trivially easy, but it may be overkill and comes with steep learning curve if you're not familiar with it.
Take a look at letter_opener gem. It was created by Ryan Bates, the Railscasts guy.

Ruby on rails: What is the most simple way to show one post per page with permalink

Right now under my posts controller i have methods
def main
#post = Post.all
end
def show
#post = Post.find(params[:id])
end
I am wondering what is the most basic and simple way to show one post per page and have next and previous links to it. Here i am referencing to main.html.erb . So for instance just have localhost:3000/posts and under that page i can have next and previous links to browse through the post.
Would I be needing some kind of ajax to this? If not then how i can do this using simple activerecord and other elements of rails?
Note: After I click on next, i do need to have the permalink of the post in the url tab.
You could do something like this. Add previous and next method to your model
def previous
posts = where('id > ?', id).limit(1)
if posts.nil?
nil
else
posts.first
end
end
def next
posts = where('id < ?',id).limit(1)
if posts.nil?
nil
else
posts.first
end
end
and then in your view you could do something like this.
unless #post.next.nil? #to show the link to the next post
link_to #post.next
end
unless #post.previous.nil? #to show the link to the next post
link_to #post.previous
end
Anyhow this method isn't that optimized since you will add more two more database queries to get previous and next posts.
You could use the gem will_paginate and set the default per page to 1, as in:
class Post
self.per_page = 1
end
For more information about will_paginate:
https://github.com/mislav/will_paginate

Rails 3.1 Application does not automatically update div

I have a Rails 3.1 application where the view has the following link:
<%= link_to("Answer Question",question_ajaxans_path(#question.id),:remote=>true)%>
Which has the controller option:
def answer
#answer = Answer.new(:question_id=>params[:question_id])
respond_to do |format|
format.js
end
end
Which renders this partial code:
alert("it worked");
$("div#answers").append(<%= escape_javascript(render :partial=>"answers/form") %>);
Firebug shows the partial is rendered, and I have double checked my view to verify that a div with an id of answers was there.
This turorial , http://railscasts.com/episodes/205-unobtrusive-javascript?view=asciicast, seems to show that it should just load and so do other ones I find on the web. But, I don't think that is the case.
Thanks to this post http://rails3stuff.posterous.com/#!/59899595 I realized that my problem resides in .append(). I didn't wrap the interior in quotes.

Rails calling action from view

Hopefully have a simple question here but I cannot for the life of me seem to find the answer. Just started working with RoR but came from ASP MVC before. I am having an issue rendering partial views whose local variables are not necessarily tied to the variables of the main view. For instance, with a blog I am trying to render a sidebar that will link to the archive.
def sidebar
#blog_posts = Blog.all(:select => "created_at")
#post_months = #blog_posts.group_by { |m| m.created_at.beginning_of_month }
end
The partial view _sidebar is as follows:
<div class="archives">
<h4>Blog Archive</h4>
<% #post_months.sort.reverse.each do |month, posts| %>
<%= link_to "#{h month.strftime("%B %Y")}: #{posts.count}", archive_path(:timeframe => month) %>
<% end %>
</div>
The problem I am having is that if I simply do a render 'sidebar' within my main view the action does not seem to be called and #post_months is always nil. Is it possible to call the action directly from the view and simply have that render 'sidebar'? In ASP MVC I used to just make the sidebar a ChildActionOnly and Render.Action from the mainview, but in RoR I am completely clueless. Any help is appreciated!
I think what's happening here is that yout sidebar is being treated as a partial and your controller method is never being called. In that case I'd put the code currently contained in the sidebar controller method into either the ApplicationHelper module or the helper module of the current view, depending on whether or not you'd need to render the sidebar from other views.
You'd need to adapt the code a bit to work in a module. Rather than setting a session variable you should have the methods return the values you want.
Module SomeModule
def blog_posts
Blog.all :select => "created_at"
end
def post_months
blog_posts.group_by { |m| m.created_at.beginning_of_month }
end
end
Of course, that may very well need to be refactored and might not work as written, but that's the general idea I'd go with.
Good Luck.

Resources