Ruby on Rails Ajax with Remote Forms - ruby-on-rails-5.2

Hello when I add the comment in my application in the form that I have with ajax, I have to reload the browser to upload the comment. In the browser I get this error that I supposedly have in this file:
(function() {
$(document).on("ajax:success", "form#comments-form", function(ev, data) {
console.log(data);
$(this).find("textarea").val("");
return $("#comments-box").append("<li> " + data.body + " - </li>");
});
$(document).on("ajax:error", "form#comments-form", function(ev, data) {
return console.log(data);
});
}).call(this);
I have this file in comments.coffe like this:
$(document).on "ajax:success", "form#comments-form", (ev,data)->
console.log data
$(this).find("textarea").val("")
$("#comments-box").append("<li> #{data.body} - </li>")
$(document).on "ajax:error", "form#comments-form", (ev,data)->
console.log data
If you can help me, I thank you.

I had the same problem and, solve it by doing the following
In the folder app/asset/javascripts/application.js look for the next line
//= require rails-ujs and change for // require rails-ujs
In this way that library is not called and will not generate conflict with jquery.
I hope it helps you

<%=
form_for([#article,#comment], remote: true, html: { id: "comments-form", :"data-
type" =>
"json" }) do |f| %>
<% if #comment.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(comment.errors.count, "error") %> prohibited this comment
from
being saved:</h2>
<ul>
<% comment.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :body %>
<%= f.text_area :body %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>

Related

Rails 4 Error: undefined method[]' for nil:NilClass`

I'm trying to setup a messaging system in my site using the Mailboxer gem in Rails 4.
When my app gets to this code:
def fetch_params(key, *subkeys)
params[key].instance_eval do
case subkeys.size
when 0 then self
when 1 then self[subkeys.first]
else subkeys.map{|k| self[k] }
end
end
it returns the error: undefined method '[]' for nil:NilClass
I've tried to figure this out, but I'm not very experienced. I've been following this tutorial: http://jamestansley.com/2014/02/22/customizing-the-mailboxer-ruby-gem-2/
I tried removing the line of code returning the error just to see what would happen, after which I received the error wrong number of arguments (1 for 2..6).
Can anyone attempt to explain this code to me? Been having a really rough time implementing this feature.
view/conversations/_form:
<%= simple_form_for :conversation, url: :conversations do |f| %>
<%= f.input :recipients %>
<%= f.input :subject %>
<%= f.input :body %>
<div class="form-actions">
<%= f.button :submit, class: 'btn-primary' %>
<%= submit_tag 'Cancel', type: :reset, class: 'btn btn-danger' %>
</div>
<% end %>
view/conversations/show:
<h1><%= #conversation.subject %> </h1>
<!--may have to work on this view. don't know if i did the haml conversion correctly-->
<h1> <%= conversation.subject %> </h1>
<ul>
<% content_tag_for(:li, conversation.receipts_for(current_user)) do |receipt| %>
<%= message = receipt.message %>
<h3><%= message.subject %> </h3>
<p><%= message.body %> </p>
</ul>
<% render 'messages/form', conversation: conversation %>
<% end %>
And here's my github repo: https://github.com/portOdin/GoFavorIt-Heroku/blob/8cd19ff5b61eb805dc694a6586f50df608752be2/app/views/conversations/show.erb

my final step in the rails app, how to make comments appear in a popup?

This is the last remaining item to complete my first rails app and need some help.
On each user profile (localhost:3000/users/username), there's a listing of posts that the user has made. Associated with each post are comments. So post_id: 3 could have comments.
I have it working already in view form but I need the comments to appear in a popup instead when the "Comments" link under each post is clicked.
I have already applied facebox which is a jQuery-based lightbox that displays popups.
I just need to move what's currently shown in show.html.erb into a popup.
There's the _comment_form.html.erb which renders into _post.html.erb
<%= link_to #, :rel => "facebox-#{post.id}" do %>
+<%= post.comments.count.to_s %>
<% end %>
<div class ="ItemComments"><% if post.comments.exists? %>
<% post.comments.each do |comment| %>
<%= image_tag("http://www.gravatar.com/avatar.php?gravatar_id=#{Digest::MD5::hexdigest(comment.user.email)}" %>
<span class="users"><%= link_to comment.user.name, comment.user %></span>
<span class="timestamp"><%= time_ago_in_words(comment.created_at) %> ago</span>
<span class="content2"><%= comment.comment_content %></span>
<% end %>
<% end %></div>
The above renders into _post.html.erb using:
<%= render 'shared/comment_form', post: post if signed_in?%>
Then it renders into show.html.erb
I'm trying to use this line, but what do I link it to?
<%= link_to #, :rel => "facebox-#{post.id}" do %>
+<%= post.comments.count.to_s %>
<% end %>
This is shared/_comment.html.erb
<% if post.comments.exists? %>
<% post.comments.each do |comment| %>
<%= image_tag("http://www.gravatar.com/avatar.php?gravatar") %>
<%= link_to comment.user.name, comment.user %>
<span class="timestamp"><%= time_ago_in_words(comment.created_at) %> ago</span>
<span class="content2"><%= comment.comment_content %></span>
<% end %>
<% end %>
One way of doing this is to render your comments into a hidden div and give that div an id. Next you point your link to the id of the div using # followed by the id. It would look something like this:
_post.html.erb
<%= link_to "#comments", :rel => "facebox" do %>
<%= post.comments.count.to_s %>
<% end %>
<div id="comments">
<%= render 'shared/comment_form', post: post if signed_in?%>
</div>
CSS
#comments {
display: none;
}
See the 'Divs' heading over at the Facebox docs.

add form (non-nested) dynamically in rails

pls can someone explain how I can dynamically add another copy of a form in rails?...been working on this for almost 2hrs. I messed around with .clone() and .appendTo in jquery, but it didnt work. Also, most of the materials I found online (like on railscast #196 and stackoverflow) focused heavily on nested forms. My form is nested, but I actually just want to add the parent form again. The photos which are nested use the html multiple attributes so I'm guessing that will handle multiple files upload for each parent form (btw I'm using paperclip).
If I just need to modify the railscast code please let me know.
Thanks.
<%= form_for(#user_book, html: { multipart: true }) do |f| %>
<% if #user_book.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#user_book.errors.count, "error") %> prohibited this user_book from been saved:</h2>
<ul>
<% #user_book.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<p>hello</p>
<% end %>
</ul>
</div>
<% end %>
<%= f.text_field :title, placeholder: "enter title...", id: "book_title" %>
<%= f.text_field :category, placeholder: "enter category..." %>
<%= file_field_tag 'user_book[user_book_photos_attributes][][photo]', :multiple => true do |p| %>
<%= p.file_field :photo %>
<% end %>
<div class="actions">
<%= f.submit %>
</div>
<% end %>

rails ajax request doesn't work

I have some problem with ajax
This request GET http://localhost:3000/projects/new (304 Not Modified) does work, it executes javascript from response:
$('#add-project-button').hide();
$('#project-form').append("<form accept-charset=\"UTF-8\" action=\"/projects\" class=\"new_project\" data-remote=\"true\" id=\"new_project\" method=\"post\"><div style=\"margin:0;padding:0;display:inline\"><input name=\"utf8\" type=\"hidden\" value=\"✓\" /><input name=\"authenticity_token\" type=\"hidden\" value=\"gzu9DETiVV8N+OtRnkdYpD6aa0/RbM7i2H+nkQ0yXGc=\" /><\/div>\n <div class=\"field\">\n <label for=\"project_name\">Name<\/label><br />\n <input id=\"project_name\" name=\"project[name]\" size=\"30\" type=\"text\" />\n <\/div>\n <div class=\"actions\"><input name=\"commit\" type=\"submit\" value=\"Create Project\" /><\/div>\n<\/form>");
But another request POST http://localhost:3000/projects (200 OK) seems ok but response is empty, no javascript is executing, but the server answer is ok:
Rendered tasks/_task.html.erb (0.0ms)
Rendered projects/_project.html.erb (4.5ms)
Rendered shared/_create.js.erb (5.4ms)
Rendered projects/create.js.erb (6.1ms)
Completed 200 OK in 96ms (Views: 8.6ms | ActiveRecord: 84.9ms)
So I'm guessing that the browser somehow is of not supposed to execute javascript from server in this case.
What might be a problem? How to make browser receive the javascript and execute it? Thanks.
UPDATE: The form which is making ajax request:
<%= form_for(#project, :remote => true) do |f| %>
<div class="field">
<%= f.label :name %><br />
<%= f.text_field :name %>
</div>
<div class="actions"><%= f.submit %></div>
<% end %>
The controller action:
def create
#project = current_user.projects.build(params[:project])
respond_with(#project.tap(&:save))
end
Maybe the problem is causing by using partial as layout, projects/create.js.erb:
<% render :layout => '/shared/create', locals: { obj: #project } do %>
$('#project-container').append("<%= escape_javascript render(#project) %>");
$('#add-project-button').show('fast');
$('#project-form').hide('fast', function(){ $('#project-form').empty(); });
<% end %>
The problem was very simple, I forget to put <%= sign in erb, so it should be:
<%= render :layout => '/shared/create', locals: { obj: #project } do %>
$('#project-container').append("<%= escape_javascript render(#project) %>");
$('#add-project-button').show('fast');
$('#project-form').hide('fast', function(){ $('#project-form').empty(); });
<% end %>

Form validation after ajax request

I'm using Rails 3.2 and I'm making my first Ajax request.
This is my code:
def create
#post = Post.find(params[:post_id])
#comment = Comment.new(params[:comment])
respond_to do |format|
if #comment.save
format.html {
redirect_to #post
}
format.js
else
format.html {
render 'posts/show'
}
format.js
end
end
end
So, I understand that I return a js template.
So, question 1: Is really a good idea to use this approach instead the standard sending json / receiving json in a $.ajax call?
My create.js.erb:
$(".commentlist").append("<%= escape_javascript(render(:partial => #comment)) %>");
Working perfectly.
But... how I validate the form? (Without ajax works perfectly).
I'm seeing that the js.erb is like the html.erb but with js instead of html (I still see this weird, I think that is easier to use controller.coffee, but I will learn this way too :)).
So question 2: How I validate ? I see that what I get in the ajax call is the entire html and my two action vars (#post and #comment).
Just that, I need to learn the Rails approach to do ajax :)
P.S: My _form.html.erb:
<%= form_for comment, :url => post_comments_path(comment.post), :remote => true do |f| %>
<% if comment.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(comment.errors.count, "error") %> prohibited this comment from being added:</h2>
<ul>
<% comment.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<%= f.hidden_field :post_id %>
<p>
<%= f.label :name %>
<%= f.text_field :name %>
</p>
<p>
<%= f.label :email %>
<%= f.text_field :email %>
</p>
<p>
<%= f.label :url %>
<%= f.text_field :url %>
</p>
<p>
<%= f.label :content %>
<%= f.text_area :content %>
</p>
<p class="no-border">
<%= f.submit "Post", :class => "button" %>
</p>
<% end %>

Resources