Customize in filename rails issue - ruby-on-rails

I'm trying to customize the format when i'm saving to xls :
I want help customizing= "Date" + "ejecutive selected" + ".xls"
My models
class Policy < ActiveRecord::Base
unloadable
belongs_to :ejecutive
has_many :policy
def self.search(search)
if search
find(:all, :conditions => ["ejecutive_id = ? ", search.to_i ] )
else
find(:all)
end
end
end
class Ejecutive < ActiveRecord::Base
has_many :policies
end
Here is my controller.
Here i put my format that i'm trying to customize with date + ejecutive selected + .xls
class PolicyManagement::PolicyController < ApplicationController
def generate_print_ejecutive_comercial
#ejecutives = Ejecutive.find(:all)
#search = Policy.search(params[:search])
#policies = #search.paginate( :page => params[:page], :per_page =>10)
#results= Policy.search(params[:search])
respond_to do |format|
format.html
format.xls { send_data render_to_string(:partial=>"report_by_ejecutive"), :filename => Date + #ejecutives.name"reporte.xls" }
end
end
Here is my view
<% form_tag :controller=>"policy_management/policy",:action =>"generate_print_ejecutive_comercial", :method => 'get' do %>
<%= select_tag "search", options_for_select(#ejecutives.collect {|t| [t.name.to_s+" "+t.lastname1.to_s,t.id]}) %>
<%= submit_tag "Search", :name => nil %>
<% end %>
Results
<% #policies.each do |policy| %>
<p> <%= policy.num_policy%> </p>
<p> <%= policy.ejecutive.name %> </p>
<p> <%= policy.ejecutive.last_name %> </p>
<% end %>
<%= will_paginate #policies %>
<%= link_to "Export", :controller=>"policy_management/policy",:action=>"generate_print_ejecutive_comercial" ,:format=>"xls",:search => params[:search],:page => params[:page] %>
I tried this
respond_to do |format|
format.html
format.xls { send_data render_to_string(:partial=>"report_by_ejecutive"), :filename => Date + #ejecutive.name + ".xls" }
end

You cannot + something to the Date class or a specific date like Date.today. But the following works.
:filename => "#{Date.today}#{#ejecutive.name}.xls"
"#{something}" evaluates something, calls to_s on the result and inserts its into the string.

Related

NoMethodError (undefined method `name' for nil:NilClass)

I am trying to upload images without gem to a model called "Course Classifications", before I was using the gem "Paperclip".
Rails Version is Rails 3.0.10
When I am trying to create a "Course Classification", I get the following error:
undefined method `name 'for nil: NilClass
I suppose it must be something regarding the image that I am trying to upload, because when I do not load an image, the model is created normally.
according to my console the error is in the line of the method 'create' 'if #course_clasification.save'
What can be?
The 'puts' throw me the following:
"PARAMS: {\"name\"=>\"Prueba12312\", \"description\"=>\"\", \"status\"=>\"1\", \"picture\"=>#<ActionDispatch::Http::UploadedFile:0x0055ffb16c36d8 #original_filename=\"Selección_250.png\", #content_type=\"image/png\", #headers=\"Content-Disposition: form-data; name=\\\"course_clasification[picture]\\\"; filename=\\\"Selecci\\xC3\\xB3n_250.png\\\"\\r\\nContent-Type: image/png\\r\\n\", #tempfile=#<Tempfile:/tmp/RackMultipart20210722-21412-xnr47e>>}"
"NAME: Prueba12312"
My code is the following:
Controller:
def create
#course_clasification = CourseClasification.new(params[:course_clasification])
p "PARAMS: #{params[:course_clasification]}"
if params[:course_clasification].present?
file = params[:course_clasification][:picture]
File.open(Rails.root.join('public','uploads', file.original_filename), 'wb') do |f|
f.write(file.read)
end
end
respond_to do |format|
if #course_clasification.save
format.html { redirect_to(course_clasifications_path, :notice => 'Classification was created') }
format.xml { render :xml => #course_clasification, :status => :created, :location => #course_clasification }
else
format.html { render :action => "new" }
format.xml { render :xml => #course_clasification.errors, :status => :unprocessable_entity }
end
end
end
def upload
uploaded_io = params.require(:course_clasification).permit(:picture)
File.open(Rails.root.join('public','uploads',uploaded_io.original_filename), 'wb') do |file|
file.write(uploaded_io.read)
end
end
Model:
class CourseClasification < ActiveRecord::Base
has_many :courses
has_many :enrollments
validates :name, presence: true
=begin
has_attached_file :avatar
# Validate content type
validates_attachment_content_type :avatar, content_type: /\Aimage/
# Validate filename
validates_attachment_file_name :avatar, matches: [/png\Z/, /jpe?g\Z/]
# Explicitly do not validate
do_not_validate_attachment_file_type :avatar
=end
scope :actives, -> { where('status = 1') }
scope :inactives, -> { where('status = 0') }
end
Form:
<%= form_for(#course_clasification, html: { style: "flex-direction: column; width: 50%;", :multipart => true }) do |f| %>
<div class="actions">
<%= link_to '<i class="fa fa-chevron-circle-left" aria-hidden="true"></i> Regresar'.html_safe, course_clasifications_path, class: "btn-button button--indigo" %>
<%= f.submit((" " + t('action.save')).html_safe, :alt => "Guardar", :title => "Guardar", :class => "button__submit btn-button button--green", :style => "font-family: FontAwesome, verdana, sans-serif; float: right; margin-top: 0; margin-right: 7px;") %>
</div>
<% lang = current_user.localization.languaje %>
<% if #course_clasification.errors.any? %>
<div id="error_explanation">
<h2><%= t('activerecord.errors.template.header', count: #course_clasification.errors.size, model: t('activerecord.models.course_clasification')) %>:</h2>
<p>
<%= t('activerecord.errors.template.body') %>
</p>
<ul>
<% #course_clasification.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field field-full" style="margin-top: 40px;">
<%= f.label t('str_name_areas_'+ lang) %><br />
<%= f.text_field :name %>
</div>
<div class="field field-full">
<%= f.label "Agregar imágen a player" %><br />
<%= f.file_field :picture %>
<%# if #course_clasification.avatar? %>
<%# image_tag #course_clasification.avatar.url(:thumb) %>
<%# end %>
</div>
<% end %>
Schema:
class CreateCourseClasification < ActiveRecord::Migration
def self.up
create_table :course_clasifications do |t|
t.string :name
t.text :description
t.boolean :status
t.string :picture
t.timestamps
end
end
end
One problem that I'm seeing is that you're not using Strong Parameters.
That means that
#course_clasification = CourseClasification.new(params[:course_clasification])
Will basically try to create an empty object since non of the params is whitelisted (whatever is not whitelisted is basically omitted by Rails), so the ActiveRecord object is invalid and the save fails.
Change it to something like
def course_classification_params
# make sure to list all the save params!
params.permit(:name, :description, :status, ...)
end
#course_clasification = CourseClasification.new(course_classification_params[:course_clasification])

Rails4 -undefined method `name' for nil:NilClass 4

I am getting an error message that says undefined method 'name' in my show.html.erb page. Where it says #book.category.name it keeps saying undefined method name.
show.html.erb
<h1><%= #book.title %></h1>
<h3><%= #book.author %></h3>
<h4>Category: <%= #book.category.name %></h4>
<p><%= #book.description %></p>
<%= link_to "Back", root_path %>
<% if user_signed_in? %>
<% if #book.user_id == current_user.id %>
<%= link_to "edit", edit_book_path(#book) %>
<%= link_to "Delete", book_path(#book), method: :delete, data: {confirm: "Are you sure you want to delete book?"} %>
<% end %>
<% end %>
Books_Controller.rb
class BooksController < ApplicationController
before_action :find_book, only: [:show, :edit, :destroy, :update]
def index
if params[:category].blank?
#books = Book.all.order("created_at DESC")
else
#category_id = Category.find_by(name: params[:category]).id
#books = Book.where(:category_id => #category_id).order("created_at DESC")
end
end
def show
end
def new
#book = current_user.books.build
#categories = Category.all.map{ |c| [c.name, c.id]}
end
def create
#book = current_user.books.build(book_params)
#book.category_id = params[:category_id]
if #book.save
redirect_to root_path
else
render 'new'
end
end
def edit
#categories = Category.all.map{ |c| [c.name, c.id]}
end
def update
#book.category_id = params[:category_id]
if #book.update(book_params)
redirect_to book_path(#book)
else
render ' new'
end
end
def destroy
#book.destroy
redirect_to root_path
end
private
def book_params
params.require(:book).permit(:title, :description, :author, :category_id, :book_img)
end
def find_book
#book = Book.find(params[:id])
end
end
Book.rb
class Book < ActiveRecord::Base
belongs_to :user
belongs_to :category
has_attached_file :book_img, :styles => { :book_index => "250x350>", :book_show => "325x475>" }, :default_url => "/images/:style/missing.png"
validates_attachment_content_type :book_img, :content_type => /\Aimage\/.*\Z/
end
Category.rb
class Category < ActiveRecord::Base
has_many :books
end
Just make sure that specific book has category or just cover it into if statement like below:
<% if #book.category %>
<h4>Category: <%= #book.category.name %></h4>
<% end %>
In case you have to leave category empty is use #try:
<h4>Category: <%= #book.category.try(:name) %></h4>
You need to make sure that the instance #book has a category object.
<h4>Category: <%= #book.category ? #book.category.name : "This book has no category" %></h4>

Nested attributes for has_many relationship

My models are
class History < ActiveRecord::Base
belongs_to :projects_lkp
has_many :pictures
accepts_nested_attributes_for :pictures
end
class Picture < ActiveRecord::Base
belongs_to :history
validates_presence_of :pics
end
history/new.html.erb
<%= form_for(:history, :url => {:action => 'create'}) do |d| %>
<%= render(:partial =>"form",:locals => {:d => d}) %>
<% end %>
history/_form.html.erb
<%= d.fields_for :pictures do |dd| %>
<div class="row form-group"></div>
<div><class='col-md-5 form-label'>Photo</div>
<%= dd.file_field :pic, multiple: true, :class => 'col-md-15' %>
</div>
<% end %>
history_controller
def create
#history = History.new(history_params)
#history.projects_lkp_id = params[:projects_lkps_id]
respond_to do |format|
if #history.save
format.html{ redirect_to histories_path(id: #history.id), notice:"History added" }
else
#history = History.where(item: #history.item).all
format.html { render 'index' }
end
end
end
def history_params
params.require(:history).permit(:history,:date,:pic)
end
But when I tried to submit form, it says that unpermitted parameter :pictures
Parameter passing is:
Parameters: {"utf8"=>"✓", "authenticity_token"=>"xE8d/mD1pXh/2AIKrZlRoL552iEBVZ7jkzLJB1kNZyE=", "history"=>{"history"=>" jhafjkaalkds", "date"=>"20/10/2014", "pictures"=>{"pic"=>[#<ActionDispatch::Http::UploadedFile:0x0000000143d1f8 #tempfile=#<Tempfile:/tmp/RackMultipart20150910-2753-1ml2hmf>, #original_filename="Firefox_wallpaper.png", #content_type="image/png", #headers="Content-Disposition: form-data; name=\"history[pictures][pic][]\"; filename=\"Firefox_wallpaper.png\"\r\nContent-Type: image/png\r\n">]}}, "projects_lkps_id"=>"", "commit"=>"Submit"}
Unpermitted parameters: pictures
Here the :pic is the attachment field created by using paperclip gem
Try this:
def history_params
params.require(:history).permit(:history, :date, pictures_attributes: [:pic])
end
One more problem I can see is with your form. It should be:
<%= form_for(:history, :url => {:action => 'create'}, multipart: true) do |d| %>
<%= render(:partial =>"form",:locals => {:d => d}) %>
<%= d.fields_for :pictures do |dd| %>
<div class="row form-group"></div>
<div><class='col-md-5 form-label'>Photo</div>
<%= dd.file_field :pic, multiple: true, :class => 'col-md-15' %>
</div>
<% end %>
<% end %>
Parameters should be in the form:
"history" => { ... , "photos_attributes" => { "0" => { ... } } }
I have found the answer for that :)
history controller
def new
#histories = History.new
#histories.pictures.build
end
history/new
<%= form_for(#histories, :url => {:action => 'create'}, html: {multipart:true}) do |d| %>
<%= render(:partial =>"form",:locals => {:d => d}) %>
<% end %>
it works :)

rails faux active record

I am trying to use faux active record (a model that has no persistence in db).
I followed this example:
https://quickleft.com/blog/using-faux-activerecord-models-in-rails-3/
And I have this error:
ArgumentError in SearchController#new
wrong number of arguments (2 for 1)
app/models/search.rb:32:in assign_attributes'
app/models/search.rb:27:ininitialize'
app/controllers/search_controller.rb:4:in new'
app/controllers/search_controller.rb:4:innew'
It seems that when you call Search.new it needs the parametters but my goal is to make it an empty Search object.
Here are my model, controller, view, route:
Model
class Search
include ActiveModel::MassAssignmentSecurity
TRUE_VALUES = ActiveRecord::ConnectionAdapters::Column::TRUE_VALUES
attr_accessor :query
attr_reader :safe_search, :results_per_page
alias_method :safe_search?, :safe_search
attr_accessible :query, :safe_search, :results_per_page
RESULTS_PER_PAGE = [10, 25, 50, 100].freeze
include ActiveModel::Conversion
include ActiveModel::Validations
validates :query, presence: true
validates :results_per_page, presence: true, inclusion: { in: RESULTS_PER_PAGE }
def persisted?
false
end
def initialize(attributes = {})
assign_attributes(attributes)
yield(self) if block_given?
end
def assign_attributes(values, options = {})
sanitize_for_mass_assignment(values, options[:as]).each do |k, v|
send("#{k}=", v)
end
end
def results_per_page=(value)
#results_per_page = value.to_i
end
def safe_search=(value)
#safe_search = TRUE_VALUES.include?(value)
end
end
Controller
class SearchController < ApplicationController
def new
#search = Search.new
render "search/new.html.erb"
end
def create
#search = Search.new(params[:search])
# TODO: use the #search object to perform a search. Adding
# a `results` method on the search object might be a good starting point.
end
end
View: search/new.html.erb
<%= form_for #search do |f| %>
<%= f.label :query %>
<%= f.text_field :query %>
<%= f.label :safe_search %>
<%= f.check_box :safe_search %>
<%= f.label :results_per_page %>
<%= f.select_box :results_per_page %>
<%= end %>
Here is the solution that I found:
In the model I am using this:
def initialize(attributes = {})
assign_attributes(attributes)
end
def assign_attributes(attributes)
sanitize_for_mass_assignment(attributes).each do |k, v|
send("#{k}=", v)
end
end
Here are my new and create methods in the controller:
def new
#search = Search.new
render "search/new.html.erb"
end
def create
#search = Search.new(params[:search])
respond_to do |format|
format.html { render :template => "search/create.html.erb" }
end
end
By the way i had to rename my controller to SearchesController because controllers must be pluralized.
And here is my new.html.erb view:
<%= form_for #search, url: { action: "create" }, :method => :post do |f| %>
<%= f.label :query %>
<%= f.text_field :query %>
<%= f.label :safe_search %>
<%= f.check_box :safe_search %>
<%= f.label :results_per_page %>
<%= f.select(:results_per_page, [10, 25, 50, 100]) %>
<%= f.submit %>
<% end %>
I hope this will be useful to somebody.

Can't mass-assign protected attributes when using accepts_nested_attributes_for and polymorphic

I've read through lots of posts here and still cant figure this one out.
I have a forum_post model and a links model. I want to nest the links form with the forum_post form but keep getting a Can't mass-assign protected attributes: links.
ForumPost Model
class ForumPost < ActiveRecord::Base
attr_accessible :content, :links_attributes
has_many :links, :as => :linkable, :dependent => :destroy
accepts_nested_attributes_for :links, :allow_destroy => true
end
Links Model
class Link < ActiveRecord::Base
attr_accessible :description, :image_url, :link_url, :linkable_id, :linkable_type, :title
belongs_to :linkable, :polymorphic => true
end
Forum_post View
<%= form_for(#forum_post) do |f| %>
<% if #forum_post.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#forum_post.errors.count, "error") %> prohibited this forum_post from being saved:</h2>
<ul>
<% #forum_post.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :content %><br />
<%= f.text_area :content, :rows => 5 %>
</div>
<%= f.fields_for :link do |link| %>
<%= render :partial => 'links/link', :locals => { :f => link} %>
<% end%>
<div class="actions">
<%= f.submit %>
</div>
<% end %>
Link View Partial
<div class="field">
<%= f.label :link_url %><br />
<%= f.text_field :link_url, :id => "url_field" %>
</div>
<div id="link_preview">
</div>
ForumPosts Controller
class ForumPostsController < ApplicationController
def new
#forum_post = ForumPost.new
respond_to do |format|
format.html # new.html.erb
format.json { render json: #forum_post }
end
def create
#forum_post = ForumPost.new(params[:forum_post])
respond_to do |format|
if #forum_post.save
format.html { redirect_to #forum_post, notice: 'Forum post was successfully created.' }
format.json { render json: #forum_post, status: :created, location: #forum_post }
else
format.html { render action: "new" }
format.json { render json: #forum_post.errors, status: :unprocessable_entity }
end
end
end
Links Controller
class LinksController < ApplicationController
def find_linkable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
def index
#linkable = find_linkable
#links = #linkable.links
end
def create
#linkable = find_linkable
#link = #linkable.links.build(params[:link])
if #link.save
flash[:notice] = "Successfully saved link."
redirect_to :id => nil
else
render :action => 'new'
end
end
end
Well, according to your question the protected attributes that you can't mass-assign is :links.
Not sure how that happened, but have you tried attr_accessible :links?
As for the security implications, it is the reason github got hacked once https://gist.github.com/1978249, and I would highly discourage setting whitelist_attributes to false.

Resources