I am trying to render the user detail on index page when user is clicked.
I am having the list of users in index page like
<% #users.each do |user| %>
<%= link_to user.name, '', {:id => user.id, :name => 'user', :remote => true}
<% end %>
In my javascript
$('#mydiv').html("<%= escape_javascript(render(:partial => '/users/show', :locals => {:id => #{params['id']}})) %>"
but I couldn't able to render the user details, because param 'id' is not passing to this page.
How to get this param and render the partial in the index page when user is clicked.
In this case you should review your code a little. You should directly call the show method in your link and edit your controller to have it responding to JavaScript:
View code:
<%= link_to user.name, user_path(user), remote: true %>
Controller code:
def show
#user = User.find(params[:id])
respond_to do |format|
format.html
format.js
end
end
And create a new view called users/show.js.erb
$("#mydiv").html("<%= escape_javascript(render(:partial => '/users/user_show', :locals => {:user => #user})) %>");
This view is calling a partial view where you can render all your user data. This view is called users/_user_show.html.erb
<div class="myuser">
<%= user.name %>
</div>
Hope that helps
Related
I have a projects/show.html.erb page. A project has_many project_messages and from the projects/show.html.erb page, a user can create a new project_message successfully, however, when the new project_message is created through a _formpartial, the page refreshes.
I want to use :remote => true to add project_messages to the project without having to refresh the page.
Please see the code I used below. This does not work and the page still refreshes. I am new to rails so any help would be greatly appreciated.
Please see the code for each file below
In projects/show.html.erbto display the project_message and create a new project_message, I have the following code which is successful:
<div class="au-chat au-chat--border">
<div class="au-message-list">
<% #project.project_messages.each do |project_message| %>
<%= render partial: 'project_messages/project_message', locals: { project_message: project_message } %>
<% end %><br>
</div>
<div class="au-chat-textfield">,
<%= render partial: 'project_messages/form', locals: { project_message: #project_message } %>
</div>
</div>
In the project_messages_controller.rb file the create method is as follows, I have added format.js { }
def create
#project_message = ProjectMessage.new(project_message_params)
#project_message.user_id = current_user.id if current_user
#project_message.project_id = current_user.team.project_id if current_user
respond_to do |format|
if #project_message.save
format.html { redirect_to #project_message.project }
format.json { render :show, status: :created, location: #project_message }
format.js { }
else
format.html { render :new }
format.json { render json: #project_message.errors, status: :unprocessable_entity }
end
end
end
The project_message _form partial then includes the :remote => true
<%= form_with(model: project_message, local: true, :remote => true) do |form| %>
<% if project_message.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(project_message.errors.count, "error") %> prohibited this project_message from being saved:</h2>
<ul>
<% project_message.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= form.text_field :pMessage, id: :project_message_pMessage, :class => 'au-input au-input--full au-input--h65', placeholder: 'Type a message' %>
<div class="actions" >
<%= form.submit "Send" %>
</div>
<% end %>
I then created a new create.js.erb file in views/project_messages/create.js.erb and added the following code:
# confirm file called
console.log('create.js.erb file');
# add new comment to end of comments section
$("#project_message").append("<%= j render(#project_message) %>");
With the code above, the page still refreshes.
When I remove local: true from the project_message _form partial, it does not refresh and creates the model but the projects/show.html.erb view is not updated!
I used the following link here and also other posts on stackoverflow
respond_to do |format|
format.js { render 'project_messages/create.js'}
end
it seems you are using Rails 5
remove remote: true and local: true from your code
read about this in here
and make sure that you a html element with id = project_message
your code is $("#project_message").append("<%= j render(#project_message) %>");
so check your HTML code , is there any element with ID like that
you can use traditional form_for http://guides.rubyonrails.org/working_with_javascript_in_rails.html#remote-elements
update below code in your views
<%= form_for project_message, :remote => true do |form| %>
and make sure that you a html element with id like <div class="au-message-list" id="project_message">
Sorry for the long title. I don't know how I got stuck this much.
I wanted to have a button (actually a link_to styled as a button) for FOLLOW / UNFOLLOW on remote. That's a Follow model where records are stored for Corporation and User (a User can follow a Corporation). The follow/unfollow links are on the Corporation show page.
<% if user_signed_in? %>
<% if Follow.where(corporation_id: #corporation.id, user_id: current_user.id).first.nil? %>
<%= link_to 'FOLLOW', {:controller => "follows", :action => "create", :user_id => current_user.id, :corporation_id => #corporation.id}, remote: true, :method => "post", class: "btns follow", id: "follow1" %>
<% elsif %>
<%= link_to 'UNFOLLOW', {:controller => "follows", :action => "destroy", :corporation_id => #corporation.id, :user_id => current_user.id }, remote: true, :method => "delete", class: "btns unfollow", id: "unfollow" %>
<% end %>
<% end %>
These are the controller actions:
def create
#corporation_id = params[:corporation_id]
#follow = Follow.new(follow_params)
#follow.save
respond_to do |format|
format.js {render :file => "/corporations/create.js.erb" }
end
end
def destroy
#corporation_id = params[:corporation_id]
attending.destroy
#attending is a method where the follow is defined. This is ok.
respond_to do |format|
format.js {render :file => "/corporations/destroy.js.erb" }
end
end
I'm rendering create.js.erb in corporations, since the change has to happen there. If I leave it as format.js, it'll search in the follows folder which is empty.
The create.js.erb look like this:
$("#unfollow").click(function(){
$("unfollow").replaceWith("<%= escape_javascript(render :partial => "corporations/profile/follow", :locals => {corporation_id: #corporation_id}) %>");
});
Btw, I tried .html instead of replaceWith, but it's not that.
The destroy.js.erb is similar. And the _unfollow.html.erb partial is like this:
<% if !#corporation.nil? %>
<%= link_to 'UNFOLLOW', {:controller => "follows", :action => "destroy", :corporation_id => #corporation.id, :user_id => current_user.id }, :method => "delete", class: "btns unfollow", remote: true, id: "unfollow" %>
<% else %>
<%= Rails.logger.info("First here") %>
<%= Rails.logger.info(corporation_id) %>
<%= link_to 'UNFOLLOW', {:controller => "follows", :action => "destroy", :corporation_id => corporation_id.to_i, :user_id => current_user.id }, :method => "delete", class: "btns unfollow", remote: true, id: "unfollow" %>
<%= Rails.logger.info("Now here...") %>
<% end %>
Without the first condition it just fires up an error the corporation_id (it's same with locales[:corporation_id]) is not defined and similar.
I have no idea what to try now... All the tutorials on the net are quite simple but the remote action is just one action in the controller where it needs to change, this has to go to another controller then back, then again to Follow... I'd really appreciate the help.
I have a invoice form in which i want to add option to print invoice on form submit. for this i have added a button and made some changes in controller.Here is my code
In invoice form:
<%= form_for #invoice do |f| %>
:
**Invoice fields**
:
<%= f.submit "Save", :name=>"save", :class=>'btn btn-success' %>
<%= f.submit "Save & Print", :name=>"save_and_print", :class=>'btn btn-default' %>
<% end %>
And in my controller i did this:
def create
:
:
if params[:save_and_print]
format.html { redirect_to("/invoices/#{#invoice.id}?save_and_print=1", :notice => 'Invoice has been saved and printed.') }
else
format.html { redirect_to(#invoice, :notice => 'Invoice has been saved.') }
end
end
def show
:
:
respond_to do |format|
format.pdf do
template=Invoice.get_template(#company, "Invoice", params[:dlc])
pdf=InvoicePdf.new(#invoice, view_context, #receipt_vouchers)
send_data pdf.render, :filename=>"#{#invoice.invoice_number}.pdf", :disposition=>"inline", :type=>'pdf'
end
end
end
And here is my link to print pdf:
<%= link_to raw('<i class="icon-print"> </i>'), invoice_path(#invoice, :format => 'pdf'), :target=>"_blank", :title=>"Print" %>
I am thinking to create an onload function to trigger generate pdf link on view page load after form submit. Any help would be appreciated.
The reason why it is not redirecting to invoice view screen is because of this line if params[:save_and_print],it should be if params[:submit] == "save_and_print"
if params[:submit] == "save_and_print" #here
format.html { redirect_to("/invoices/#{#invoice.id}?save_and_print=1", :notice => 'Invoice has been saved and printed.') }
else
format.html { redirect_to(#invoice, :notice => 'Invoice has been saved.') }
end
You should be accessing the value passed to the submit button through giving params[:submit].
I have got a simple solution for my problem. First of all i gave id to my print pdf link and than call that link on page load. Here is my solution :
<%= link_to raw('<i class="icon-print"> </i>'), invoice_path(#invoice, :format => 'pdf', :dlc=>"no"), :class => 'btn btn-white btn-lg', :id=>"print1-inv", :target=>"_blank", :title=>"Print" %>
and script on show.html.erb:
<% if !params[:save_and_print].blank? && params[:save_and_print]=="1" %>
<script>
$(document).ready(function(){
$("#print1-inv")[0].click();
});
</script>
<% end %>
this code works for me.
For a certain employee I have a report. Each report has some shifts. Each shift can be corrected. I am migrating from Ruby 2 to Ruby 3. I am working with partial pages. When I click on Correct, a partial page appears, when I click on Update, page should go back to the partial page Details with the ID of that employee.
_modify_item.html.erb:
<%= form_for :modified_item, :url => {:action => :modify_item, :report_id => #monthly_report.id, :modified_item_id => #modified_item.id,remote: true} do |form| %>
<table width=100% height=100%>
<td width=150 style='border: 0px; background-color: #eee' align=center>
<%= form.hidden_field :report_id, :value => #monthly_report.id %>
<%= submit_tag 'Update', :name => 'update', :value => 'Update', :class => 'highlighted_button' %>
<%= link_to 'Cancel',
{:action => 'details', :report_id => #monthly_report.id},
:class => 'highlighted_button',
remote: true %>
</td>
</tr>
</table>
<% end %>
controller.rb:
def modify_item
#modified_item = Employee::MonthlyReportItem.find(params[:modified_item_id])
#monthly_report = #modified_item.report
begin
#modified_item.update_attributes!(params[:modified_item])
flash[:notice] = 'Position was updated.'
flash[:warning]=#modified_item.verification_problems if !#modified_item.correct?
redirect_to('/accounts/salary/details', :report_id => #monthly_report.id) and return
rescue Exception => e
flash.now[:error] = "Some of the values are missing or are incorrect. Try again."
end
#render(:partial => 'details') and return
end
modify_item.js.erb: (tried didn't succeed)
//$("#salary_popup").html("<%= j(render partial: 'details') %>");
Update: Forgot to mention the exact error which points inside of the if
Couldn't find Employee::MonthlyReport without an ID
Rails goes into details function and tries this:
def details
if params[:item].nil?
#monthly_report = Employee::MonthlyReport.find(params[:report_id])
else
#monthly_report = Employee::MonthlyReport.find(params[:item][:report_id])
end
..
end
Does the hidden field you create have the name attribute? If not trying adding that.
I'm trying to allow users to favorite posts and then it show them sort of of interaction through AJAX, but it's not working.
The error I'm getting in the console is:
ActionView::Template::Error (undefined local variable or method `post_item' for #<#<Class:0x007fecb2a3d5f8>:0x007fecb2a357e0>):
The button is being rendered through a partial:
<%= render "shared/fave_form", post_item: post_item %>
Here's the code for the button (shared/_fave_form.html.erb):
<% if current_user.voted_on?(Post.find(post_item)) %>
<%= link_to "unlike", vote_against_post_path(post_item.id), :remote => true, :method => :post, :class => "btn") %>
<% else %>
<%= link_to "like", vote_up_post_path(post_item.id), :remote => true, :method => :post, :class => "btn") %>
<% end %>
Here's the toggle.js.erb file:
$("#fave").html("<%= escape_javascript render('fave_form') %>");
When you render the partial using toggle.js.erb it is not getting locals value post_item, you have to provide it in also.So, your js code should be something like following
$("#fave").html("<%= escape_javascript(render :partial=>"fave_form", locals: {post_item: post_item}).html_safe %>);
I guess you are using some ajax call and then your toggle.js.erb so in your toggle action you must specify value to post_item, lets make it instance variable #post_item so that we can use it in toggle.js.erb.
$("#fave").html("<%= escape_javascript(render :partial=>"fave_form", locals: {post_item: #post_item}).html_safe %>);
The partial is using a local variable, so pass post_item as a local:
<%= render :partial => "shared/fave_form", :locals => {post_item: post_item} %>