0

I have a page with a form I'd like to see the results of without reloading in my rails app, but I'm new to incorporating JS in ruby on rails. I've tried following along Display result data without page refresh on form submission in ruby on rails as well as a few 'intro to AJAX' guides, but am struggling to apply them to my own project.

In my user profile profile.html.erb, I have a list of tags for a review

<% if review.tags.length > 0 %>
  <% review.tags.each do |tag| %>
    <%= tag.category %>
    <%= tag.name %>
  <% end %>
<% end %>

Under which there's a form to add a new tag

<%= simple_form_for @tag, url: "/add_tag/#{review.id}" do |form| %>
  <%= form.input :category %>
  <%= form.input :name %>
  <%= form.button :submit %>
<% end %>

(I'm currently using the gem simple_form for formating reasons. It's not the cause of my confusion, though I think I might need to remove it to apply a solution)

This form submits to my reviews_controller, which has this method add_tag

def add_tag
  @review = Review.find_by(id: params[:id])
  tag_cat = params[:tag][:category]
  tag_name = params[:tag][:name]
    
  if valid_tag(tag_cat, tag_name) && tag_cat != ""
    @tag = grab_tag(tag_cat, tag_name)
    if ReviewTag.find_by(tag_id: @tag.id, review_id: @review.id).nil?
      ReviewTag.create(tag_id: @tag.id, review_id: @review.id)
    end
    redirect_to '/profile'
  else
    redirect_to '/profile'
  end
end

The redirect_to /profile works just fine at the moment, though it seems I need to use format.js in some way instead? I'm struggling to see what changes I need to make on the javascript and view side.

Adrave
  • 3
  • 1

1 Answers1

1

Looks like you try fill form data and save it in one action. If i am right understand you issue you have Review and Review has many review tags. And you try added this tags on page where you working with Review model and you want edit Review data and ReviewTag data on one page without reloading. You need to use nested_attributes and create form how edited ReviewTag from javascript. Recomend to see this guide https://www.pluralsight.com/guides/ruby-on-rails-nested-attributes

It works like this:

  1. on Review model add accepts_nested_attributes_for :review_tags
  2. on page where you edit Review model added block like form.fields_for :review_tags do |builder|
  3. on the same page added a button like create tag and added js onclick action - this action create a form for new ReviewTag. Read this - How to Create a Form Dynamically Via Javascript

If you need to validate you new tag dynamicly you can call ajax for do it

  • I'm actually just adding a single `ReviewTag` to a preexisting `Review`, but this is close enough to clear up what I needed, especially as I think I have somewhere else I'll be using `nested_attributes` now, thanks! – Adrave Apr 11 '21 at 23:02