i have a table with set of students, I want update attendance column to all the students with different values using single form which will save all the record.
note: i was able to save all the records individually.
here is my edit page
<table>
<thead>
<tr>
<th>Name</th>
<th>user_id</th>
<th>Present days</th>
<th>Total days</th>
<th colspan="3"></th>
</tr>
</thead>
<tbody>
<% #attendancce.each do |userr| %>
<tr>
<%= form_for(userr) do |f| %>
<td><%=userr.user.name %></td>
<td><%= userr.user_id %></td>
<td><%= f.number_field :present_days %></td>
<td><%= f.number_field :total_days %></td>
<td><%= f.submit %></td>
<% end %>
</tr>
<% end %>
</tbody>
</table>
<%= submit_tag "submit" %>
and below is my method for updating the records
def update
#attendancce = Attendance.all
respond_to do |format|
if #attendance.update(attendance_params)
format.html { redirect_to #attendance, notice: 'Attendance was successfully updated.' }
format.json { render :show, status: :ok, location: #attendance }
else
format.html { render :edit }
format.json { render json: #attendance.errors, status: :unprocessable_entity }
end
end
end
please suggest how to achieve my target
Related
im new with rails. currently im facing problem with it. i have 3 model which is
order, task, and order task.
in the ordertask, i try to pass id from show.html to edit.html, but the rails only pass
http://localhost:3000/orders_tasks/%23%3COrderTask::ActiveRecord_Relation:0x00000009c9a078%3E/edit
instead of id number.
here is my show.html.erb
<p id="notice"><%= notice %></p>
<table class="table table-hover">
<tr>
<td>Task
</td>
<td>Status:
</td>
</tr>
<tr>
<% #status.each do |i| %>
<td><%= i.task_id %>
</td>
<td><%= i.status %>
</td>
</tr>
<% end %>
</table>
<%= link_to 'Edit', edit_orders_task_path(#status) %> |
<%= link_to 'Back', orders_tasks_path %>
here is my ordertask controller
class OrdersTasksController < ApplicationController
before_action :set_status, only: [:show, :edit, :update]
def index
#orders = Order.all
#status = OrderTask.includes(:task,:order).where(order_id: params[:id])
end
def edit
end
def show
end
def update
respond_to do |format|
if #status.update(order_params)
format.html { redirect_to #status, notice: 'Order was successfully updated.' }
format.json { render :show, status: :ok, location: #order }
else
format.html { render :edit }
format.json { render json: #status.errors, status: :unprocessable_entity }
end
end
end
private
# Use callbacks to share common setup or constraints between actions.
def set_status
#status = OrderTask.includes(:task,:order).where(order_id: params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def order_params
params.require(:order_task,:order).permit(:order_id,:status)
end
end
and here is my edit.html
<%= form_for(#status, html: {class: 'form form-horizontal'}).first.id do |f| %>
<% if #status.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#status.errors.count, "error") %> prohibited this order from being saved:</h2>
<ul>
<% #status.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<table class="table table-hover">
<tr>
<td><%= f.label "List of task" %>
</td>
<td><%= f.label "Status" %>
</td>
</tr>
<tr>
<td><%= f.task_id %>
</td>
<td><div class="dropdown">
<%= f.select(:status,['In progress', 'Completed'], {}, {class: "control"})%> </div>
</td>
</tr>
<tr>
<td>
</td>
<td><%= f.submit %>
</td>
</tr>
</table>
<% end %>
my order model
class Order < ActiveRecord::Base
belongs_to :staff
belongs_to :customer
belongs_to :service
has_many :order_task
has_many :tasks , through: :order_task
validates :staff_id , presence: true
end
my task model
class Task < ActiveRecord::Base
has_many :order_task
has_many :orders , through: :order_task
attr_accessor :status, :task_type
validates :task_name, presence: true, uniqueness: true
end
and lastly my order task model
class OrderTask < ActiveRecord::Base
self.primary_key = [:order_id]
self.table_name = "Orders_tasks"
belongs_to :order
belongs_to :task
end
i hope you guys can help me out cause i have stuck with this problem for a week now. :D
You should place the edit links in the loop... since #status contains multiple ordertaks, and each ordertask should have his own edit page:
<p id="notice"><%= notice %></p>
<table class="table table-hover">
<tr>
<td>Task
</td>
<td>Status:
</td>
<td>Action:</td>
</tr>
<tr>
<% #status.each do |i| %>
<td><%= i.task_id %>
</td>
<td><%= i.status %>
</td>
<td><%= link_to 'Edit', edit_orders_task_path(i) %></td>
</tr>
<% end %>
</table>
<%= link_to 'Back', orders_tasks_path %>
Edit: But I do like to point out that most of the time you're not in need of Controllers for your join models. So I do not know why you think you need it, most of the logic can be build from either the OrdersController or the TasksController.
I have added gem 'acts-as-taggable-on' -v 2.3.1 in Gemfile.
Rails version 3.2.13, Ruby -v 1.9.3
In article.rb,
class Article < ActiveRecord::Base
acts_as_taggable_on :tags
has_many :comments, dependent: :destroy
validates :title, presence: true,
length: { minimum: 5 }
end
In articles_controller.rb,
class ArticlesController < ApplicationController
before_filter :authenticate_author!, except: [:index, :show]
def index
myarray = Article.all
#articles = Kaminari.paginate_array(myarray).page(params[:page]).per(10)
end
def show
#article = Article.find(params[:id])
end
def new
#article = Article.new
end
def create
#article = Article.new(article_params)
if #article.save
redirect_to #article
else
render 'new'
end
end
def edit
#article = Article.find(params[:id])
end
def update
#article = Article.find(params[:id])
if #article.update_attributes(article_params)
redirect_to #article
else
render 'edit'
end
end
def destroy
#article = Article.find(params[:id])
#article.destroy
redirect_to articles_path
end
private
def article_params
params.require(:article).permit(:title, :text, :tag_list => [])
end
end
In articles/_form.html.erb
<div class="field">
<%= f.label :tag_list, "Tags (separated by commas)" %><br />
<%= f.text_field :tag_list %>
</div>
I ran the following commands after installing the acts-on-taggable-gem,
rails generate acts_as_taggable_on:migration
rake db:migrate
In articles/index.html.erb
<% #articles.each do |article| %>
<tr>
<td><%= article.title %></td>
<td><%= article.text %></td>
<td><%= article.tag_list %></td>
<td><%= link_to 'Show', article_path(article) %></td>
<% if author_signed_in? %>
<td><%= link_to 'Edit', edit_article_path(article) %></td>
<td><%= link_to 'Destroy', article_path(article),
method: :delete,
data: { confirm: 'Are you sure?' } %></td>
<% end%>
</tr>
<% end %>
The tags are not being displayed in the index page.
But if I do ,
article = Article.new(:title => "Awesome")
article.tag_list = "awesome, cool"
article.save
The transaction gets committed and the tags are displayed on the browser.
Why aren't the tags getting saved and displayed in the index page?
The Tag List is an array, which means you need to 'loop' to extract the data. Whenever I have used acts_as_taggable I run through a loop to extract the tags. Something like the following should work:
<% #articles.each do |article| %>
<tr>
<td><%= article.title %></td>
<td><%= article.text %></td>
<td>
<% article.tag_list.each do |tag| %>
<%= tag %>
<% end %>
</td>
<td><%= link_to 'Show', article_path(article) %></td>
<% if author_signed_in? %>
<td><%= link_to 'Edit', edit_article_path(article) %></td>
<td><%= link_to 'Destroy', article_path(article),
method: :delete,
data: { confirm: 'Are you sure?' } %></td>
<% end%>
</tr>
<% end %>
I know there are a lot of issues with wkhtmltopdf and page breaks that date back years, but I haven't worked out a solution yet. I'm using the PDFKit gem to generate my html pages into pdfs, but I don't want the pages to break in the middle of a table row.
I'm using wkhtmltopdf-binary (0.9.9.3), which looks to be the most updated version
My CSS:
#media print {
#scores table tr td, #scores table tr th {
page-break-inside: avoid !important;
}
table, tr, td, th, tbody, thead, tfoot {
page-break-inside: avoid !important;
}
}
My table:
<div class="score_table">
<table id="scores" class="print-friendly">
<tbody>
<% #chapters.each do |chapter| %>
<tr>
<th colspan="3" ><%= chapter.name %></th>
</tr>
<% chapter.rules.each do |rule| %>
<tr>
<th colspan="2" >Rule: <%= rule.name %></th>
<th></th>
</tr>
<!-- Triggers -->
<% rule.triggers.each do |trigger| %>
<tr>
<td>T</td>
<td><%= markdown(trigger.body) %></td>
<td><%= markdown(trigger.explanation) %></td>
</tr>
<% if trigger.image? || trigger.image2? %>
<tr>
<td></td>
<% if trigger.image? %>
<td><%= image_tag trigger.image.url(:thumb) %></td>
<% else %>
<td></td>
<% end %>
<% if trigger.image2? %>
<td><%= image_tag trigger.image2.url(:thumb) %></td>
<% else %>
<td></td>
<% end %>
</tr>
<% end %>
<% end %>
<!-- Questions -->
<% rule.questions.each do |question| %>
<tr>
<td>Q</td>
<td><%= markdown(question.body) %></td>
<td><%= markdown(question.answer) %></td>
</tr>
<% if question.image? || question.image2? %>
<tr>
<td></td>
<% if question.image? %>
<td><%= image_tag question.image.url(:thumb) %></td>
<% else %>
<td></td>
<% end %>
<% if question.image2? %>
<td><%= image_tag question.image2.url(:thumb) %></td>
<% else %>
<td></td>
<% end %>
</tr>
<% end %>
<% end %>
<!-- Hints -->
<% rule.hints.each do |hint| %>
<tr>
<td>H</td>
<td><%= markdown(hint.body) %></td>
<td><%= markdown(hint.explanation) %></td>
</tr>
<% if hint.image? || hint.image2? %>
<tr>
<td></td>
<% if hint.image? %>
<td><%= image_tag hint.image.url(:thumb) %></td>
<% else %>
<td></td>
<% end %>
<% if hint.image2? %>
<td><%= image_tag hint.image2.url(:thumb) %></td>
<% else %>
<td></td>
<% end %>
</tr>
<% end %>
<% end %>
<% end %>
<% end %>
</tbody>
</table>
</div>
Is there a work around, or is there something that I'm doing wrong? This is the result:
I could post the PDFKit code as well, but it sounds like a wkhtmltopdf issue
***Update - My CSS #print isn't affecting the page when .pdf is added to the url. I have my stylesheet link with media: "all"
<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => true %>
Here's my initializer pdfkit.rb:
ActionController::Base.asset_host = Proc.new { |source, request|
if request.env["REQUEST_PATH"].include? ".pdf"
"file://#{Rails.root.join('public')}"
else
"#{request.protocol}#{request.host_with_port}"
end
}
If I can fix the CSS, then I probably will solve the page break issue!
i added this in css it worked for me
#media print {
#scores {
page-break-before: always;
}
}
I am using version wkhtmltopdf 0.12.0
For me, page breaks ONLY work with --print-media-type.
Without it, page break protection for images works, but not page-break-after or before.
I had to make a special css file for print media to get it work.
Setting the paper size to 'A3' or using the 'overflow: visible' didn't make any difference.
I ended up with the following:
in config/initializers:
PDFKit.configure do |config|
config.wkhtmltopdf = '/usr/bin/wkhtmltopdf'
config.default_options = {
:encoding=>"UTF-8",
:page_size => 'A3',
:zoom => 0.9,
:javascript_delay => 2000,
:print_media_type => true,
:footer_right => 'report, page [page] of [toPage]',
:no_background => true,
}
end
I am not 100% sure if the no_background is needed.
Then, in the controller:
def report_as_pdf
require 'nokogiri'
root_url = Rails.env.development? ? 'http://localhost:3000' : 'https://my.example.com'
html = render_to_string(layout: true, template: "reports/report_as_pdf").gsub('/assets', root_url + '/assets') # since wkhtmltopdf can not find the css files, we add the root_url to all assets
html_doc = Nokogiri::HTML(html)
html_doc.css('div.contain-to-grid').remove
html_doc.css('nav#rapportage_bar').remove
# Had to remove certain elements on the page. Not relevant for this particular problem, but it may help.
html = html_doc.to_html
filename = 'report_' + Time.now.to_s(:db)[0..9]
if Rails.env.development?
File.write("/tmp/#{filename}.html", html)
render :text => "wrote /tmp/#{filename}.html"
fork do
system("wkhtmltopdf --footer-right 'report, page [page] of [toPage]' --page-size 'A3' --zoom 0.9 --javascript-delay 2000 --no-background --print-media-type file:////tmp/#{filename}.html /tmp/#{filename}.pdf")
end
# forking was the only way I could get it to work in development mode, using thin as webserver instead of webrick (but it might work with webrick, I didn't try).
else
kit = PDFKit.new(html)
send_data(kit.to_pdf, :filename => filename + '.pdf', :type => 'application/pdf')
# all is simpeler in production mode.
end
end
Note, that in the default layout (normally app/views/layouts/application.html.erb) I added one line to introduce a special css file for print:
stylesheet_link_tag "application_print", media: "print"
This file actually imports some tables from ZURB Foundation, which is cool.
#import "foundation/components/tables";
h1 {
font-variant: small-caps;
font-weight: bolder;
font-size: 320%;
border-bottom: 12px solid black;
margin-bottom: 20px;
margin-top: 80px;
}
h2 { (etc etc etc)
To make page breaks in a view, I just insert this in the right places:
I hope this will be useful to someone someday.
Can you upload the controller code where you've called PDFkit.new ?
Your stylesheet might not be included.
Try adding the stylesheet in your controller code like this:
def export
kit = PDFKit.new(render_to_string(layout: false, handlers: [:haml], formats: :html, template: 'score_tables/export'))
kit.stylesheets << "#{Rails.root}/vendor/assets/stylesheets/bootstrap.css"
kit.stylesheets << "#{Rails.root}/app/assets/stylesheets/score_tables.css"
kit
end
Here is how I fixed my issue.
- Updated PDFKIT to as of ( 01/22/2014 )
- I had to move my table out of the <div> as the nested table messes everything up.
Example:
No div tag wrapping the table.
From
<div class="score_table">
<table id="scores" class="print-friendly">
...rest of the HTML
To
<table id="scores" class="print-friendly">
...rest of the HTML
Hope this helps.
When trying csv export in rails, I am getting these values only
`#<User:0x007f4a41859980> #<User:0x007f4a41835c88>
my controller file ps4_controller.rb
def csv_export
#users = User.order(created_at: :desc)
respond_to do |format|
format.html
format.csv { render text: #users.to_csv }
format.xls { render text: #users.to_csv(col_sep: "\t") }
end
end
model file ps4.rb
class Ps4 < ActiveRecord::Base
attr_accessible :username, :email, :school, :batch
def self.to_csv(users)
CSV.generate do |csv|
csv << column_names
users.each do |ps4|
csv << ps4.attributes.values_at(*column_names)
end
end
end
end
view file csv_export.xls.rb
<table>
<thead>
<tr>
<th>Username</th>
<th>Email</th>
<th>School</th>
<th>Batch</th>
</tr>
</thead>
<tbody>
<% #users.each do |user| %>
<tr>
<td><%= user.username %></td>
<td><%= user.email %></td>
<td><%= user.school %></td>
<td><%= user.batch %></td>
</tr>
<% end %>
</tbody>
</table>
Can anybody plz help?
In controller:
respond_to do |format|
...
format.csv { send_data #users.to_csv, filename: "users-#{Date.today}.csv" }
end
In model (do not send any attributes to to_csv method):
def self.to_csv
attributes = %w{id email}
CSV.generate(headers: true) do |csv|
csv << attributes
all.each do |user|
csv << attributes.map{ |attr| user.send(attr) }
end
end
end
#users is an array of users, and you are trying to call to_csv method on the array. On the other hand the to_csv method is defined as a class method, meaning you need to invoke it on the class itself:
format.csv { render text: User.to_csv(#users) }
I want to update a model on my db. if an user checked the checkbox, it must not be appear again on the view.
I have some view like this:
<%= form_tag( riepilogo_path, method: "post", id: "sel") do %>
<%= hidden_field_tag "sala", params[:sala] %>
<%= hidden_field_tag "spectacle_id", params[:spectacle_id] %>
<%= hidden_field_tag "num", params[:num] %>
<table>
<tr>
<th></th>
<th>Numero</th>
</tr>
<% for posti in #postis %>
<tr>
<td><%= check_box_tag "posti_ids[]", posti.id %></td>
<td><%=h posti.numero %></td>
</tr>
<% end %>
</table>
<%= submit_tag "OK", id: "sub"%>
<% end %>
controller of Postis is something like so:
class PostisController < ApplicationController
def index
#postis = Posti.where(:stato => "unchecked" , :spectacle_id => params[:spectacle_id] , :hall_num => params[:sala])
end
def posti_multiple
#postis = Posti.find(params[:posti_ids])
end
end
In the Posti's model i have attributes: spectacle_id, hall_num, seat(integer) and stato (:default => "unchecked").
When he submit, seats be load in posti_ids[]. I want to update stato of seats which are present in posti_ids from "unchecked" to "checked".
As per your comment,you have tried to perform update_column on an Array.So is the error
undefined method `update_column' for # Array:0xb881584
Here #postis returns.You should be giving it like this
Posti.update_column(stato: "checked")