AJAX forms and snippets

I have successfully integrated comments into public activity following a tutorial on public activity #406 Public Activity. However, I am facing issues with submitting the comments via ajax. I have gone through several tutorials but haven't been able to resolve the issue. Here is an excerpt of my code:

This is how the comments controller looks like:

def create
    @activity = Activity.find(params[:activity_id])

    @comment = @activity.comments.create!(comment_params)
    @comment.user = current_user
    @users= User.joins(:comments).where(talks: {id:     @activity.talk_ids}).push(@comment.user).reject {|user| user == @comment.user }.uniq

        @users.each do |user|
          @comment.create_activity :create, owner: user
        end
        
        respond_to do |format|
          format.html { redirect_to user_path(current_user), notice: 'Comment created.' }
          format.js
        end
  end

This is a snippet of the partial I created for each activity:

<div class="media social-box">

  <a class="pull-left social-users-avatars" href="#">

    <%= link_to image_tag(activity.user.image.url(:small)) ,activity.user%>
    <p><%= link_to activity.user.username, activity.user if feed.activity %>
      <span style="font-size: 11px; color:#4edee1;">Added this item </span> </p>

  </a>

  <ul class="unstyled custumer_say">
    <li class="clearfix" style="list-style: none">
      <%= link_to  image_tag(sell.image.url,:style=> "width: 40%; padding-right: 10px;", :class=> "pull-left img_client"), sell%>

   <div class="entry-content">
        <header>
          <span class="entry-date">&mdash;  <%="#{time_ago_in_words(sell.created_at)} ago "%> </span>
        </header>


      </div>

    </li>
  </ul>

  <div class="media-body social-body">

    <div class="social-footer">

      <div class="social-info-users">
        <strong><%= pluralize(activity.comments.size, "Comment")  %></strong>
      </div>

      <div class="social-comments">

        <ul id="chat">
          <%= render activity.comments %>
        </ul>

        <% if current_user.friends.present? %>

            <div class="media">
              <a class="pull-left" href="#">

                <%=  image_tag(current_user.image.url(:tiny),:style=> "width: 100%;")%>
              </a>
              <div class="media-body">
                <%= form_for([activity, activity.comments.build],:remote => true) do |f| %>
                    <%= f.text_field :details, :class=>"input-block-level", :placeholder=>"write a comment" %>

                <% end%>

              </div>
            </div>


        <% end %>

      </div>

    </div>
  </div>
</div>

I want to update the CSS id as follows:

<ul id="chat">
              <%= render activity.comments %>
            </ul> 

The content of my create.js.erb file is:

$("#chat").append('<%= j render(activity.comments) %>');
$("#new_comment")[0].reset();

It's worth noting that my partial is rendered as

<%= render activity.comments %>
instead of the more common
<%= render @activity.comments %>
, which works correctly. The entire code is displayed on the showpage of the current user (e.g., users/1 page).

Answer №1

There are a few issues here:

@comment.user = current_user

Have you initialized the @comment variable somewhere in your code? It seems like you're referencing a variable that may not have been created yet, unless it's being called in a before_action callback.


Are any error messages showing up? Without some indication of what might be wrong, it's difficult to analyze large amounts of code. Please provide some feedback or logs from your application to give us insight into how it's handling requests.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Using Jquery to target an element within the same DOM element and apply changes

My website platform doesn't assign any IDs or classes to the menus it generates, and uses nested lists for submenus. To make the submenus expand upon clicking, I created a jQuery script: $(function () { $(".wrapper ul li").click(function () { ...

In internet explorer with AJAX, the UI is refreshed by Javascript only when an alert() function is triggered

Having an issue in Internet Explorer, works perfectly in Firefox. There is a javascript function that updates the UI (screen content) before an AJAX call. However, it does not update the UI unless an alert box prompt is used. Without the alert box, the UI ...

The deployment on heroku encountered an error during the build process

I'm attempting to deploy my React application on Heroku, but I keep encountering the following errors: -----> Installing dependencies Installing node modules npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ...

Unlock the potential of Bootstrap 4 in Vue.js 2 without the need for bootstrap-vue

I'm interested in finding a way to incorporate bootstrap 4 into my vue.js 2.6 framework. Despite the abundance of tutorials available, many of them are outdated as of late 2020, or they insist on using bootstrap-vue, which introduces unwanted addition ...

Attempting to pass a limit argument to a query in urql, Strapi, and Next JS for the Query.posts field has resulted in a combination of errors including graphQLErrors

I need help figuring out how to pass a variable for the limit parameter in my GraphQL query. I am currently working with urql, Strapi, and its GraphQL plugin in a Next.js application. My goal is to introduce a variable for the limit to restrict the number ...

The screen suddenly turns black just moments after starting the video

Currently, I am utilizing the Youtube JavaScript API to embed videos on my webpage and control a playlist. However, I keep encountering an error where the video turns black right after loading the title, play icon, and loading icon. Initially, it seems lik ...

Converting the given data into an object in JavaScript: a step-by-step guide

"[{'id': 3, 'Name': 'ABC', 'price': [955, 1032, 998, 941, 915, 952, 899]}, {'id': 4, 'Name': 'XYZ', 'id': [1016, 1015, 1014, 915, 1023, 1012, 998, 907, 952, 945, 1013, 105 ...

There was an error with the response code of 500 on the development server for react-native

An issue has been encountered on the node.js window: error: bundling failed: Error: Unable to resolve module react-native-gesture-handler from node_modules\@react-navigation\native\src\Scrollables.js: react-native-gesture-handler could ...

JavaScript encountering a NaN value

I'm encountering an issue where I am receiving a NaN when attempting to summarize columns of a report. Additionally, my query is only retrieving 1 row of data, but the grid is displaying 2 rows. Does anyone have any suggestions on how to resolve this ...

Attempting to confirm the validity of my form

I have been attempting to validate my form in JSP, but unfortunately it is not working as expected. The form runs fine, however, the function 'validatemark' from my JavaScript file is not being called. Below is a snippet of my code: <%@ ...

Ways to effectively hide one window or pop-up upon clicking another

I am working on creating an interactive website for my close circle of friends and family. One of the key features is to have a button that displays their biography when clicked. What I'm aiming for is that when a different bio is selected, the previo ...

What is the most effective method to query Prisma using a slug without utilizing a React hook?

Retrieve post by ID (slug) from Prisma using getStaticProps() before page generation The challenge arises when attempting to utilize a React hook within getStaticProps. Initially, the plan was to obtain slug names with useRouter and then query for a post ...

Displaying or concealing list elements in Angular 6

I am working on a simple Angular app that displays a list of items. I want the behavior to be such that when the first item in the list is clicked, its description (card) should be displayed. And, if the second item is clicked and its description is displa ...

Encountering the error of receiving "$ undefined," despite making a reference to the library

I have included the JQuery library in the following way: <script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js" type="text/javascript"></script> Despite trying to download the library and include it locally in my project, I ...

My attempt at creating a straightforward sorting function turned out to be ineffective

My attempt at creating a basic sorting function seems to be failing as it is still returning the original list instead of the sorted one. function sortByPopular (collection) { let items = collection.slice(); items.sort(function(a,b) { re ...

Using Angular to dynamically access component properties

Seeking assistance with creating dynamic Tabs in TabView of PrimeNG. The components are displaying properly, but I am unsure how to access their properties. I am following the guidelines provided at https://angular.io/guide/dynamic-component-loader and us ...

The navigation bar options are not collapsing as intended

When I resize my page to width:750px;, my navigation bar is not collapsing the items. Despite trying to edit my CSS, I am still clueless. Here is my live page. This is the CSS for my slidebar: @media (max-width: 480px) { /* Slidebar width on extra small ...

Tips for showcasing my database in real-time using Php, JavaScript, jQuery and AJAX

Is there a way to display my MySQL database in real-time through AJAX without overloading it with excessive queries? I am currently utilizing jQuery's load function, but I suspect there may be a more efficient method. Can you offer any advice or alter ...

When the next button is clicked, the button content disappears

I am struggling with a problem involving two buttons that store tables. The issue is, I want the table to disappear when the second button is clicked and show the contents of the second button immediately after clicking it once, rather than having to click ...

Get your hands on large files with ease by utilizing jQuery or exploring alternative methods

Within my User Interface, there exists an Advanced Search section where the user can select from 7 different options as depicted in the diagram. Based on these selections, a web service is triggered. This web service returns search results in JSON format, ...