How to render/fetch a template remotely through StimulusJS? - ruby-on-rails

So following is the bit of code that I'd like to add in the HTML after a particular event occurs:
<div class='comment-form' data-controller='comment'>
<form action='' data-action='comment#createComment'>
<div class='comment-form__title'>Add your reply:</div>
<textarea class='comment-form__textarea' placeholder='Type in your reply' data-comment-target='commentText'></textarea>
<input type="submit" value="Submit" class='btn-secondary' >
</form>
</div>
As of now, the only way I could find, is the following:
post.insertAdjacentHTML(`<div class='comment-form' data-controller='comment'>
<form action='' data-action='comment#createComment'><div class='comment-form__title'>Add your reply:</div><textarea class='comment-form__textarea' placeholder='Type in your reply' data-comment-target='commentText'></textarea><input type="submit" value="Submit" class='btn-secondary'></form></div>`)
I'm looking for a way where this template is rendered through the server code(read: Rails), instead of me hardcoding it in the JS.
P.S:
As of writing this, Discourse for StimulusJS is down, and I could find a link for a question similar to what I'm asking here: https://discourse.stimulusjs.org/t/fetching-a-partial-on-click/1297, and on Stackoverflow, I couldn't find a relevant question to this.

If you looking to render the comment form continuously. You can use the loop like this:
<div class='post-comments-section'>
<% post.comments.each do |comment| %>
<div class="post-comments">
<p>
<b><%= comment.user.name %>:</b> <%= comment.content %>
</p>
<span> <%= comment.created_at.strftime("%Y/%m/%d") %> </span>
</div>
<% end %>
<%= form_for(post.comments.new, url: post_comments_path(post)) do |form| %>
<%= form.text_field :content, id: :comment_content, class: 'form-control', placeholder: 'Add new Comment' %>
<%= form.submit 'Comment', class: 'btn btn-secondary' %>
<% end %>
</div>
And, If you are looking to add something specific. You can add the partial from the controller with a condition.
def create
if comment.create
render partial: "posts/comment"
end
end

Related

How to create dropdown with rails form using bootstrap?

The form tag below works. However, I wanted to add styling and substitute text_field_tag into dropdown select so user can select the hours.
<%= form_tag("/availability", method: "post") do %>
<%= label_tag(:available_hour, "Add Availability:") %>
<%= text_field_tag(:available_hour) %>
<%= submit_tag("Add") %>
<% end %>
I am having trouble creating form with dropdown select using bootstrap form. I tried:
<form method="post" action="/availability">
<select class="custom-select">
<% (1..24).to_a.each do |el| %>
<option value=el><%= el%></option>
<% end %>
</select>
<button type="submit" class="btn btn-primary">Submit</button>
</form>
But it gave me ActionController::InvalidAuthenticityToken error.
This is done inside user show view, and the action I am firing is from Availability model' create action.
I found a relevant SO post on bootstrap form, but the answer uses PHP. This is what he used: <form action="results.php" method="POST" role="form" class="form-horizontal">.
I think if I can somehow point to bootstrap to look for Availability, it should work.
How can I point out to bootstrap form which controller (and method) to use?
You're probably omitting a CSRF value that's automatically included by form_tag.
Try adding
#app/views/layouts/application.html.erb
<%= csrf_meta_tags %>
Or you can add it to the form block directly:
<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
form_tag helper link, you can add option , authenticity_token: false
actually rails already has actionview helper to help you create dropdown with hour here is link
for your problem you can try
<%= form_tag("/availability", method: "post", authenticity_token: false) do %>
<div class="row form-group">
<%= f.label "Add Availability:", :class => 'control-label col-sm-3' %>
<div class="col-sm-5">
<%= select_hour :available_hour, :class => 'form-control') %>
</div>
</div>
<button type="submit" class="btn btn-primary">Submit</button>
<% end %>

Ajax form submition not working

I'm attempting to create a "Save Changes" button for a form that would send data via ajax to the update method in the controller. The aim is to allow form users to save their work without the form reloading or redirecting. However I'm running into a bit of a problem; I'm getting the following error
undefined method `update_incorporation_path'
To be clear, incorporation is the controller that we're working with. Below is the code I added to accomplish this.
To my view, I added:
<%= button_to "", update_incorporation_path(#incorporation), :remote => true, :method => :post %>
To my routes, I added:
resources :incorporations do
member do
post 'update'
end
end
The update method looks like this:
def update
if #incorporation.update(incorporation_params)
if admin_signed_in?
#incorporations = Incorporation.all.order("created_at DESC")
else
#incorporations = current_user.incorporations("created_at DESC")
end
render action: "index"
else
render 'edit'
end
end
The complete view is below:
edit.html.erb
<%= render 'form' %>
<br/>
<%= link_to "Back", root_path, class: "btn btn-default" %>
_form.html.erb (the buttons are at the bottom)
<div id="wrapper" class="active main-content">
<%= simple_form_for #incorporation do |f| %>
<!-- Sidebar -->
<!-- Sidebar -->
<div id="sidebar-wrapper">
<ul id="sidebar_menu" class="sidebar-nav">
<li class="sidebar-brand"><a id="menu-toggle" href="#">Menu<span id="main_icon" class="glyphicon glyphicon-align-justify"></span></a></li>
</ul>
<% #sections=[["basic_info", "Basic Info"],["address", "Address"],["equity", "Equity"],["officers","Officers"],["directors", "Directors"],["contractor","Contractors"],["ip","IP"],["shareholders", "Shareholders"]] %>
<ul class="sidebar-nav" id="sidebar">
<% #sections.each do |section| %>
<li><span class="sub_icon glyphicon glyphicon-link"></span><%= section[1] %></li>
<% end %>
</ul>
<div id="save">Save</div>
</div>
<div class="panel-body">
<div id="basic_info" class="form_section">
<div class="form-left"><h2>Basic Info</h2></div>
<div class="form-right">
<%= f.simple_fields_for :company do |company| %>
<div class="padded-fields">
<%= render 'basic_fields', company:company %>
</div>
<% end =%>
<div class="padded-fields">
<div class="form_subsection">
<%= f.input :trademark_search, as: :radio_buttons, label: 'Would you like us to do a trademark search and provide advice regarding any issues we identify in relation to the name you have selected?', input_html: { class: 'form-control' } %>
</div>
</div>
</div>
</div>
<%= f.simple_fields_for :company do |company| %>
<div id="address" class="form_section">
<%= render 'address_fields' , company:company %>
</div>
<div id="equity" class="form_section">
<%= render 'equity_fields' , company:company %>
</div>
<div id="officers" class="form_section">
<div class="form-left"><h2>Officers</h2><br/><p>Please list the officers of the company.</p></div>
<div class="form-right">
<div>
<%= company.simple_fields_for :officers do |officer|%>
<%= render 'officer_fields', f: officer %>
<% end =%>
<%= link_to_add_association 'Add Officer', company, :officers, class: "btn btn-default add-button" %>
</div>
</div>
</div>
<div id="directors" class="form_section">
<div class="form-left"><h2>Directors</h2><br/><p>Please list the initial directors of the company. We recommend an odd number to avoid a deadlocked board.</p></div>
<div class="form-right">
<div>
<%= company.simple_fields_for :people do |person|%>
<%= render 'person_fields', f: person %>
<% end =%>
<%= link_to_add_association 'Add Director', company, :people, class: "btn btn-default add-button" %>
</div>
</div>
</div>
<div id="contractor" class="form_section">
<div class="form-left"><h2>Employees Contractors</h2></br><p>Please list all employees, independent contractors and any other individual or entity who will be providing services to the company at the time of incorporation. Each of these persons should have written agreements with the company. Please check the box next to each name for whom you would like us to prepare agreements</p></div>
<div class="form-right">
<div>
<%= company.simple_fields_for :contractor_people do |contractor| %>
<%= render 'contractor_person_fields', f:contractor %>
<% end =%>
<%= link_to_add_association 'Add Person', company, :contractor_people, class: "btn btn-default add-button" %>
</div>
<div class="form_subsection">
<div>
<%= company.simple_fields_for :contractor_orgs do |contractor| %>
<%= render 'contractor_org_fields', f:contractor %>
<% end =%>
<%= link_to_add_association 'Add Company', company, :contractor_orgs, class: "btn btn-default add-button" %>
</div>
</div>
</div>
</div>
<div id="ip" class="form_section">
<div class="form-left">
<h2>Intellectual Property</h2><br/><p>Please list existing intellectual property (including business plans, software, artwork, inventions, trade secrets and the like) that has been created for use in the company and the name of the person or people who created it.</p>
</div>
<div class="form-right">
<div>
<%= company.simple_fields_for :ips do |ip| %>
<%= render 'ip_fields', f: ip %>
<% end =%>
<div class="add-field"><%= link_to_add_association 'Add IP', company, :ips, class: "btn btn-default add-button" %></div>
</div>
</div>
</div>
<div id="shareholders" class="form_section">
<div class="form-left"><h2>Shareholders</h2><br/><p>Please list all individuals to hold equity in this company.</p></div>
<div class="form-right">
<div>
<%= company.simple_fields_for :shareholders do |shareholder|%>
<%= render 'shareholder_fields', f: shareholder %>
<% end =%>
<%= link_to_add_association 'Add Shareholder', company, :shareholders, class: "btn btn-default add-button" %>
</div>
</div>
</div>
<% end =%>
</div>
<%= f.button :submit, id:"incorporation_submit", class: "btn btn-primary" %>
<%= button_to "Update", incorporation_path(#incorporation), method: :post, remote: true %>
<% end =%>
</div>
I figure I must be forgetting something. Any thoughts are much appreciated.
Routes for update method was by default added when you wrote resources :incorporations, so change your routes to
resources :incorporations
And your path should be incorporation_path, also method in button_to is by default post, you don't need to write it,
change your button_to to
<%= button_to "Update", incorporation_path(#incorporation), :remote => true %>
But, if you are submitting a form, it should have a submit button instead of button_to, your form should look like this
<%= form_for #incorporation, remote: true do |f| %>
# form content
<%= f.submit "Submit" %>
<% end %>
Hope this helps!
Instead of :
<%= button_to "", update_incorporation_path(#incorporation),
:remote => true, :method => :post %>
Try :
<%= button_to "Update", incorporation_path(#incorporation),
method: :post, remote: true %>
In your route:
resources :incorporations
The resources ships with default actions index,new, create,edit, update, destroy. You don't need to declare it manually.
You can verify the routes from your console.
rake routes | grep 'incorporations'
You will get output like :
From here you can construct your path for the update action.
Hope it helps :)

How do I render a new form instead of an edit on a show action?

I have a Post model, and depending on who is reading the Post#Show page I would like to change the form that is available.
How do I do that?
i.e. if a user.has_role? :guest, and they hit the form button, they should see a new (and empty) form.
If a user.has_role? :editor, and they hit that same form button they should see an edit form. However, they should be able to hit a "New Post" button that basically changes that "new form" into an "edit form".
I know this breaks Rails RESTFul ways, but how do I achieve this?
Edit 1
I am using Simple_Form, so this is what my form partial looks like:
<%= simple_form_for(#post, html: {class: 'form-horizontal' }) do |f| %>
<%= f.error_notification %>
<%= f.input_field :parent_id, as: :hidden %>
<div class="row">
<div class="col-xs-12">
<% if can? :manage, #post %>
<label for="status">
Status
</label>
<%= f.input_field :status, label: "Status", collection: Post.statuses.keys, selected: :unconfirmed %>
<% end %>
<% if can? :manage, #post %>
<label for="title">
Title
</label>
<%= f.input_field :title, placeholder: "Enter Title" %>
<span id="wordCountTitle">0</span> words<br/>
<span class="help-block">A block of help text that breaks onto a new line and may extend beyond one line.</span>
<% end %>
<div class="report-field">
<label for="report">
Report
</label>
<div class="input-group">
<span class="input-group-addon"><span class="fa fa-file-text"></span>
</span>
<%= f.input_field :body, id: "body-field", placeholder: "Provide all the facts of what happened, who did it, and where it happened.", class: "form-control", rows: "4" %><br />
</div>
<span class="help-block">Please avoid speculation.</span>
<span id="wordCountBody">0</span> / 150 words
</div>
<!-- <br/>
<br /> -->
<!-- <br /> -->
<label for="name">
Check if you are an eye witness:
</label>
<%= f.input_field :has_eyewitness, boolean_style: :inline %>
<br/>
<div>
<label for="photoFileUpload">Upload Images:</label>
<%= f.input_field :photo %>
<p class="help-block">Allowed: png, gif, jpg/jpeg</p>
</div>
<div>
<label for="FileUpload">Upload Documents, Video, or Audio:</label>
<%= f.input_field :file %>
<p class="help-block">Allowed: txt, pdf, doc, docx, xls, xlsx, mp4, m4v, mp3, wav.</p>
</div>
</div>
<% if can? :manage, #post %>
<%= f.input :youtube_embed_code %> <br />
<%= f.input :soundcloud_embed_code %> <br />
<% end %>
<div class="col-xs-12">
<%= f.button :submit, class: "btn btn-primary pull-left" %>
</div>
</div> <!-- //row -->
<% end %>
This is how this form is executed in my application.html.erb
<%= render "posts/form" %>
Supply the form with a new instance of the Post model
<% if user.has_role? :guest %>
<%= form_for Post.new do |f| %>
<% end %>
<% elsif user.has_role :editor %>
<%= form_for #post do |f| %>
<% end %>
<% end %>
I would definitely reconsider this though, past you knowing it breaks RESTful ways. Have you considered what happens if there are validation errors for the guest's post?

Jquery mobile, rails, collapsibles - extra labels appearing

I'm trying to display a simple collapsible set from a rails app. It works perfectly the first time, giving me the output below.
However, when I go back to the page (via the "Save changes" form submit), additional labels are appearing, and I can't work out why:
My index.html.erb file is as follows:
<div data-role="page" data-url="<%= request.path %>">
<div data-role="header">
<h1> CB </h1>
</div>
<div data-role="content">
<div data-role="collapsible-set">
<% #gr.each do |g| %>
<div id=" <%= g %>" data-role="collapsible">
<h3> <%= g %> </h3>
<p>
<%=form_tag "/checkboxen", method: :get do %>
<% #gr2.each do |g2| %>
<%= check_box_tag "#{g}_#{g2}" %>
<%= label_tag "#{g}_#{g2}",g2 %>
<% end %>
<%= submit_tag %>
<% end %>
</p>
</div>
<% end %>
</div>
</div>
While my (very simple) checkboxen_controller.rb is this:
class CheckboxenController < ApplicationController
def index
#gr=["one","two","three"]
#gr2=["a","b","c"]
end
end
As you can probably guess, I'm a newbie to this, and can't work out why it's happening (if it matters, I've turned turbolinks off, and have no unusual javascript in the system).
I've found a work-around: instead of using <%= label_tag %> I explicitly enclosed the check_box_tag in a <label> ... </label>. Why the original didn't work is something I still haven't figured out.

Rails Generate Scaffold only shows a little bit of my post

I generated a scaffold so that i can post blog entries into my site.
I already made one for articles which works the way i wanted...
However i generated another one for reviews but when i post my reviews only a couple of sentences show and not the whole review. When i go back to edit the review most of my review is gone and only a couple of sentences shows up.....
I can't seem to add more than a couple of sentences for some reason.....
It has nothing to do with the CSS since i turned all styles off and i still get the same results
Heres the Show Page
<div class="container">
<div class="row">
<div class="span4">
<%= image_tag #comic_review.photo %>
</div>
<div class="span8 comic_review_content">
<h3>
<b><%= #comic_review.title %></b>
</h3>
<br />
<p>
<b>Synopsis:</b>
<%= #comic_review.content %>
</p>
<p>
<b>Credits:</b>
<%= #comic_review.credits %>
</p>
<h3>Review</h3>
<div class="line_section"></div>
<p><%= simple_format #comic_review.review %></p>
<%= link_to 'Edit', edit_comic_review_path(#comic_review) %> |
<%= link_to 'Back', comic_reviews_path %>
<div class="comment_count">
All Comments (<%= #comic_review.comments.count %>)
</div>
<%= render "comments/comments" %>
<%= render "comments/form" %>
</div>
Heres the actual form
<%= form_for #comic_review, :html => { :multipart => true } do |f| %>
<% if #comic_review.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#comic_review.errors.count, "error") %> prohibited this article from being saved:</h2>
<ul>
<% #comic_review.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<b>Title</b>
<br />
<%= f.text_field :title, class: 'form_field1' %>
</div>
<br />
<div class="field">
<b>Author</b>
<br />
<%= f.text_field :credits, class: 'form_field1' %>
</div>
<br />
<div class="field">
<b>Date</b>
<br />
<%= f.text_field :content, class: 'form_field1' %>
</div>
<br />
<%= f.file_field :photo, class: "photo_upload" %>
<br />
<br />
<div class="field">
<b>Content</b>
<br />
<%= f.text_field :review, rows: 25, class: 'form_field' %>
</div>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
I dont know whats going on any help would be appreciated thank you in advance
In your database, is the type of the review column VARCHAR(255)? If so, that would be because you did review:string when you generated the scaffold; string gets converted to VARCHAR(255), and at least with MySQL, if you insert a string with more than 255 characters into a column of that type, it truncates everything after the first 255 characters.
The fix is to change the column type. Log in to the mysql console unser your database, and run:
ALTER TABLE comic_reviews CHANGE review review TEXT;

Resources