Inject local variables into rails partial - html

I want my partial below to get the classy class from it being injected through locals, but I keep getting undefined method for classy.
//view
<%= render layout: "layouts/partial", locals: {className: "classy"} do %>
...
<% end>
//partial
<div class="regular-div <%=className if className?%>"></div>

To check if a local variable is set use local_assigns.has_key?(:some_key) or local_assigns[:some_key] to safely access the local variable.
A nifty way of handling the common task of building a list of classes is:
module ApplicationHelper
# Takes an array or list of classes and returns a string
# Example:
# class_list('a', 'b', nil, 'c')
# => "a b"
# class_list(['a', 'b', nil, 'c'])
# => "a b c"
def class_list(*classes)
[*classes].flatten.compact.join(' ')
end
end
Then you can do:
<div class="<%= class_list('regular-div', local_assigns[:className]) %>"></div>

Related

ArgumentError wrong number of arguments (1 for 3..4)

I get an ArgumentError for line #3 in my views/-/new.html.erb file that states:
"wrong number of arguments (1 for 3..4)"
<div class='form-group'>
<%= form.label :category %>
<%= form.select "category", options_from_collection_for_select([{1 => 'Food'}, {2 => 'Entertainment'}]) %>
</div>
The Application trace states:
app/views/events/new.html.erb:14:in block in _app_views_events_new_html_erb__1569841425540097418_70204987081640'
app/views/events/new.html.erb:5:in_app_views_events_new_html_erb__1569841425540097418_70204987081640'
erb:14 is line #3 above, and erb:5 is
<%= form_for #event do |form| %>
The error message is being thrown by options_from_collection_for_select([{1 => 'Food'}, {2 => 'Entertainment'}])
[{1 => 'Food'}, {2 => 'Entertainment'}] is an array being passed as one argument to options_from_collection_for_select method; hence the error message.
The correct form for calling the options_from_collection_for_select helper method is
options_from_collection_for_select(collection, value_method, text_method, selected = nil)
See more details and usage examples at http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/options_from_collection_for_select
I think you'd be better off using options_for_select, which will work with the arguments you've provided and just replace the options_from_collection_for_select in your code. The documentation for which can be found here.
You need to decide whether you want the number (1, 2 etc.) or the word (Food, Entertainment etc.) to be the "value" which reaches your back-end. For example:
options_for_select({'Food' => 1, 'Entertainment' => 2})
The output of the above in HTML would be as follows:
<option value="1">Food</option>
<option value="2">Entertainment</option>
The options_from_collection_for_select method requires 3 arguments. You've only provided one: [{1 => 'Food'}, {2 => 'Entertainment'}]. Your second argument should be a method/attribute on each object in the collection which represents the "value", the third should be the label for that value.

Odd rendering of an html table in Ruby on Rails when using content_tag

I'm trying to build a table in Ruby on Rails with the help of the content_tag method.
When I run this:
def itemSemanticDifferential(method, options = {})
if options[:surveyQuestion].any? then
#template.content_tag(:tr) do
#template.content_tag(:td, options[:surveyQuestion], :colspan => 3)
end
end
#template.content_tag(:tr) do
#template.content_tag(:th, options[:argument0])
end
end
Only the second part gets rendered:
#template.content_tag(:tr) do
#template.content_tag(:th, options[:argument0])
end
Can anyone tell me why this is?
Ruby Rails returns the last variable it used if no return is explicitly called.
( example: )
def some_method(*args)
a = 12
b = "Testing a String"
# ...
3
end # This method will return the Integer 3 because it was the last "thing" used in the method
Use an Array to return all the content_tag (WARNING: this method will return an Array, not a content_tag as you expect, you'll need to loop on it):
def itemSemanticDifferential(method, options = {})
results = []
if options[:surveyQuestion].any? then
results << #template.content_tag(:tr) do
#template.content_tag(:td, options[:surveyQuestion], :colspan => 3)
end
end
results << #template.content_tag(:tr) do
#template.content_tag(:th, options[:argument0])
end
return results # you don't actually need the return word here, but it makes it more readable
end
As asked by author of the Question, You need to loop on the result because it is an array of content_tags. Also, you need to use .html_safe to output the content_tags as HTML (not strings).
<% f.itemSemanticDifferential(:method, options = {}).each do |row| %>
<%= row.html_safe %>
<% end %>

Ignore modules from Model

I have in my application a few controllers that i want to use as a api. In this api i need to use versioning.
in my routes.rb i`m using this:
require 'api_constraints'
(...)
scope '/:target/:version', :module => :api, :constraints => { :version => /[0-z\.]+/ } , :defaults => { :format => 'json' } do
scope :module => :v1, :constraints => ApiConstraints.new(:version => 1, :default => true) do
match '/list' => 'sample#list'
end
end
my api_constraints.rb:
class ApiConstraints
def initialize(options)
#version = options[:version]
#default = options[:default]
end
def matches?(req)
#default || req.headers['Accept'].include?("application/waytaxi.api.v#{#version}")
end
def self.version
#version
end
end
in my SampleController.rb:
module Api
module V1
class SampleController < ApiBaseController
def list
render json: Model.find_by_id(params[:id])
end
end
end
end
the ApiBaseController:
module Api
class ApiBaseController < ApplicationController
before_filter :authenticate
skip_before_filter :verify_authenticity_token
private
def authenticate
# if params[:target] == "ios"
# render :json => {status: 404}
# return false
# end
end
end
end
the problem is:
whenever i try to call Model i get this error:
uninitialized constant Api::V1::SampleController::Model
If i use: ::Model i get this error:
uninitialized constant Model
And yes, i do have this models on my database. If i use Model.all outside the SampleController i get the objects.
P.S.: I'm using rails 3.2.8
Found my problem.
My Model was in plural and on my controller i was calling it in singular

How to assign variables when using RSpec to test jbuilder views

I am trying to write RSpec tests to test the templates I have constructed using jbuilder which ultimately serves up JSON data for my API. I have many tests in spec/controllers which test my controller functionality, but I am looking to also test that I am rendering the correct JSON fields in my jbuilder views. Here is an example of what I have setup:
# app/views/api/v1/users/create.json.jbuilder
json.first_name user.first_name
# spec/views/api/v1/users/create.json.jbuilder_spec.rb
require 'spec_helper'
describe "api/v1/users/create.json.jbuilder" do
it "renders first_name" do
assign( :user, User.create( :first_name => "Bob" ) )
render
hash = JSON.parse( rendered )
hash.has_json_node( :first_name ).with( "Bob" )
end
end
What I get when I run rspec spec/views/api/v1/users/create.json.jbuilder_spec.rb is the following error
Failures:
1) api/v1/users/create.json.jbuilder render a user
Failure/Error: render
ActionView::Template::Error:
undefined local variable or method `user' for #<#<Class:0x007fa2911c3118>:0x007fa29105f2b8>
# ./app/views/api/v1/users/create.json.jbuilder:1:in `_app_views_api_v__users_create_json_jbuilder___3806288263594986646_70168098229960'
# ./spec/views/api/v1/users/create.json.jbulder_spec.rb:6:in `block (2 levels) in <top (required)>'
No matter how I have tried to assign/create/pass a user object to the template, it fails. Any idea what I might be doing wrong?
After much reading and iteration, this is what works:
require 'spec_helper'
describe "api/v1/users/create.json.jbuilder" do
let( :user ) { User.create( :not_strict => true ) }
it "renders first_name" do
render :template => "api/v1/users/create", :locals => { :user => user }, :formats => :json, :handler => :jbuilder
rendered.should have_json_node( :first_name ).with( user.first_name )
end
end
note: the have_json_node comes from the api_matchers gem.
assigns method sets instance variables, your view should be #user.first_name instead of user.first_name, or is that a partial? if it's a partial you should do render :partial => ..., if it's a template you should use #user

Import CSV Data in a Rails App with ActiveAdmin

i want to upload CSV files through the activeadmin panel.
on the index page from the resource "product" i want a button next to the "new product" button with "import csv file".
i dont know where to start.
in the documentation is something about collection_action, but with the code below i have no link at the top.
ActiveAdmin.register Post do
collection_action :import_csv, :method => :post do
# Do some CSV importing work here...
redirect_to :action => :index, :notice => "CSV imported successfully!"
end
end
anyone here who use activeadmin and can import csv data?
Continuing from Thomas Watsons great start to the answer which helped me get my bearings before figuring the rest of it out.
The code blow allows not just CSV upload for the example Posts model but for any subsequent models thereafter. all you need to do is copy the action_item ands both collection_actions from the example into any other ActiveAdmin.register block and the functionality will be the same. hope this helps.
app/admin/posts.rb
ActiveAdmin.register Post do
action_item :only => :index do
link_to 'Upload CSV', :action => 'upload_csv'
end
collection_action :upload_csv do
render "admin/csv/upload_csv"
end
collection_action :import_csv, :method => :post do
CsvDb.convert_save("post", params[:dump][:file])
redirect_to :action => :index, :notice => "CSV imported successfully!"
end
end
app/models/csv_db.rb
require 'csv'
class CsvDb
class << self
def convert_save(model_name, csv_data)
csv_file = csv_data.read
CSV.parse(csv_file) do |row|
target_model = model_name.classify.constantize
new_object = target_model.new
column_iterator = -1
target_model.column_names.each do |key|
column_iterator += 1
unless key == "ID"
value = row[column_iterator]
new_object.send "#{key}=", value
end
end
new_object.save
end
end
end
end
note: this example does a check to see whether or not the first column is an ID column, it then skips that column as rails will assign an ID to the new object (see example CSV below for reference)
app/views/admin/csv/upload_csv.html.haml
= form_for :dump, :url=>{:action=>"import_csv"}, :html => { :multipart => true } do |f|
%table
%tr
%td
%label{:for => "dump_file"}
Select a CSV File :
%td
= f.file_field :file
%tr
%td
= submit_tag 'Submit'
app/public/example.csv
"1","TITLE EXAMPLE","MESSAGE EXAMPLE","POSTED AT DATETIME"
"2","TITLE EXAMPLE","MESSAGE EXAMPLE","POSTED AT DATETIME"
"3","TITLE EXAMPLE","MESSAGE EXAMPLE","POSTED AT DATETIME"
"4","TITLE EXAMPLE","MESSAGE EXAMPLE","POSTED AT DATETIME"
"5","TITLE EXAMPLE","MESSAGE EXAMPLE","POSTED AT DATETIME"
note: quotations not always needed
Adding a collection_action does not automatically add a button linking to that action. To add a button at the top of the index screen you need to add the following code to your ActiveAdmin.register block:
action_item :only => :index do
link_to 'Upload CSV', :action => 'upload_csv'
end
But before calling the collection action you posted in your question, you first need the user to specify which file to upload. I would personally do this on another screen (i.e. creating two collection actions - one being a :get action, the other being your :post action). So the complete AA controller would look something like this:
ActiveAdmin.register Post do
action_item :only => :index do
link_to 'Upload posts', :action => 'upload_csv'
end
collection_action :upload_csv do
# The method defaults to :get
# By default Active Admin will look for a view file with the same
# name as the action, so you need to create your view at
# app/views/admin/posts/upload_csv.html.haml (or .erb if that's your weapon)
end
collection_action :import_csv, :method => :post do
# Do some CSV importing work here...
redirect_to :action => :index, :notice => "CSV imported successfully!"
end
end
#krhorst, I was trying to use your code, but unfortunately it sucks on big imports. It eat so much memory =( So I decided to use own solution based on activerecord-import gem
Here it is https://github.com/Fivell/active_admin_import
Features
Encoding handling
Support importing with ZIP file
Two step importing (see example2)
CSV options
Ability to prepend CSV headers automatically
Bulk import (activerecord-import)
Ability to customize template
Callbacks support
Support import from zip file
....
Based on ben.m's excellent answer above I replaced the csv_db.rb section suggested with this:
require 'csv'
class CsvDb
class << self
def convert_save(model_name, csv_data)
begin
target_model = model_name.classify.constantize
CSV.foreach(csv_data.path, :headers => true) do |row|
target_model.create(row.to_hash)
end
rescue Exception => e
Rails.logger.error e.message
Rails.logger.error e.backtrace.join("\n")
end
end
end
end
While not a complete answer I did not want my changes to pollute ben.m's answer in case I did something egregiously wrong.
expanding on ben.m's response which I found very useful.
I had issues with the CSV import logic (attributes not lining up and column iterator not functioning as required) and implemented a change which instead utilizes a per line loop and the model.create method. This allows you to import a .csv with the header line matching the attributes.
app/models/csv_db.rb
require 'csv'
class CsvDb
class << self
def convert_save(model_name, csv_data)
csv_file = csv_data.read
lines = CSV.parse(csv_file)
header = lines.shift
lines.each do |line|
attributes = Hash[header.zip line]
target_model = model_name.classify.constantize
target_model.create(attributes)
end
end
end
end
So your imported CSV file can look like this (use to match up with model attributes):
importExample.csv
first_name,last_name,attribute1,attribute2
john,citizen,value1,value2
For large excel which takes time on normal process, I created a gem that process Excel sheets using an active job and display results using action cable(websockets)
https://github.com/shivgarg5676/active_admin_excel_upload
Some of the solutions above worked pretty well. I ran into challenges in practice that I solved here below. The solved problems are:
Importing CSV data with columns in different orders
Preventing errors caused by hidden characters in Excel CSVs
Resetting the database primary_key so that the application can continue to add records after the import
Note: I took out the ID filter so I could change IDs for what I'm working on, but most use cases probably want to keep it in.
require 'csv'
class CsvDb
class << self
def convert_save(model_name, csv_data)
csv_file = csv_data.read
csv_file.to_s.force_encoding("UTF-8")
csv_file.sub!("\xEF\xBB\xBF", '')
target_model = model_name.classify.constantize
headers = csv_file.split("\n")[0].split(",")
CSV.parse(csv_file, headers: true) do |row|
new_object = target_model.new
column_iterator = -1
headers.each do |key|
column_iterator += 1
value = row[column_iterator]
new_object.send "#{key.chomp}=", value
end
new_object.save
end
ActiveRecord::Base.connection.reset_pk_sequence!(model_name.pluralize)
end
end
end