wrong number of arguments (3 for 2) in semantic_form_for tag - ruby

project details
ruby 2.4.1p111 and rails 4.2.8
Below is the code from my index page.
<%= semantic_form_for #threshold_configuration, :url => dm_threshold_configuration_path do |f| %>
//my code goes here//
<% end %>
in my index action i have the instance variable set.
def index
super
#threshold_configuration = ThresholdValues.first
end
when i load the page getting below error.
wrong number of arguments (3 for 2)
If i replace the semantic_form_for as below my page is loading.
<%= semantic_form_for :threshold_configuration, :url => dm_threshold_configuration_path do |f| %>
//my code goes here//
<% end %>
i'm not getting what exactly happening in the #threshold_configuration and :threshold_configuration. syntax which im using is fine according the formstatic gem manual.
Thnx in advance
Ajith

Related

Only execute code in erb if variable exists?

Ruby newbie here who just started using Ruby with .erb templates and I'm having a problem with the code. I have a hangman game that's passing variables from the .rb file to the .erb file and everything was working fine until I tried to check it on initial load (no variables present) and it threw errors. So I figured I'd use defined? with an if statement to check if the variable exists and then execute the code if it does and ignore if doesn't. It works fine when I use:
<% if defined?bad_guesses %>
<%= bad_guesses %>
<% end %>
But the information I need is an array and when I try to use an .each or .times statement like this:
<% if defined?bad_guesses %>
<% bad_guesses.each do |i| %>
<%= i %>
<% end %>
<% end %>
I get:
NoMethodError at /
undefined method `each' for nil:NilClass
C:/Projects/hangman/views/index.erb in block in singleton class
<% bad_guesses.each do |i| %> hangman.rb in block in
erb :index, :locals => {:game_status => game_status, :bad_guesses => bad_guesses, :good_guesses => good_guesses, :word => word}
Any suggestions appreciated.
Also, is this even the proper way to do this? When you make an .erb template that uses variables passed in from a class in your .rb file, how do you ignore it until it exists to the template?
Passing variables using:
get '/' do
if params['make'] != nil
make = params['make'].to_i
game_status, bad_guesses, good_guesses, word = Hangman.get_word(make)
elsif params['guess'] != nil
guess = params['guess'].to_s
game_status, bad_guesses, good_guesses, word = Hangman.check_guess(guess)
end
erb :index, :locals => {:game_status => game_status, :bad_guesses => bad_guesses, :good_guesses => good_guesses, :word => word}
end
Looking at this:
<% if defined?bad_guesses %>
<% bad_guesses.each do |i| %>
<%= i %>
<% end %>
<% end %>
a few points:
defined?a is bad style; use defined?(bad_guesses) or defined? bad_guesses instead.
defined? checks if it's defined, so if you say foo = nil; defined? foo it will be true.
You could alternatively use this:
defined?(bad_guesses) && bad_guesses
On the other hand, undefined instance variables are nil by default:
# it shows undefined
defined? #non_existing_var
# but you can still check if it's truthy:
puts "found" if #non_existing_var
# it won't print anything
Similar to instance variables in this regard are hashes. The default value of an unknown key is nil.
The problem with instance variables is they are not scoped to the partial. Instead, I recommend sending your local variables as a nested hash:
locals: { data: { foo: "bar" } }
Then you can safely check for values which may not exist:
if data[:foo]
# this runs
elsif data[:non_existent]
# this doesnt run
end
For my purposes, the following syntax worked:
<% if some_var %>
<%= some_var %>
<% end %>
This block is rendered if some_var is not nil.

Rails 4 search bar

I'm trying to create a search bar in my Rails 4 app. I'm my user db has 'name' and 'email' columns for the user's - I want users to be able to search for other users by name or id.
I'm currently getting this:
ActiveRecord::RecordNotFound in UsersController#index
Couldn't find all Users with 'id': (all, {:conditions=>["name LIKE ?", "%hi#example.com%"]}) (found 0 results, but was looking for 2)
Does anyone know what I'm doing wrong? I've looked at railscasts and a few forums etc but cant get past this point at the moment.
index.html.erb:
<% form_tag users_path, :method => 'get' do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<% end %>
model/user.rb:
def self.search(search)
if search
find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
else
find(:all)
end
end
users_controller.rb:
def index
#users = User.search(params[:search])
end
routes.rb:
get 'search' => 'users#index'
Are you using Rails 4? find(:all, ...) is the old way of doing things. find only takes ids now. Use:
def self.search(search)
if search.present?
where('name LIKE ?', "%#{search}%")
else
where(true)
end
end
Also present? will test against both nil and blank. Keep in mind that LIKE can be really slow depending on your database.
Searching in rails
By default rails doesn't support full text searching .Activerecord finder always find a record using the primary key ie. id.
Hence , we need some other gems or applications like sunspot, elasticsearch etc..
i'll show you using Sunspot solr here ..
in the gem file of your application just add the following code...
.
gem 'sunspot_rails'
group :development do
gem 'sunspot_solr'
end
and in terminal use
bundle install
rails g sunspot_rails:install
this will add solr and creates config/sunspot.yml file
rake sunspot:solr:start
rake sunspot:reindex
edit the user.rb lile in models
app/model/user.rb
Class User < ActiveRecord::Base
searchable do
text :name, :email
end
end
in app/controller/users_controller.rb
and then add in index function
def index
#search = User.search do
fulltext params[:search]
end
#users = search.results
end
Make a form to take a user input
<%= label_tag(:search, "Search for:") %>
<%= text_field_tag(:search) %>
<%= submit_tag("Search") %>
<% end %>

String will work but not symbols in Rails

To learn Rails, I am writing a simple guestbook app that does not use a database.
Anyway, this is what my view looks like:
views/guest_book_pages/home.html.erb
<h1>Guest Book</h1>
<%= #userinput %>
<%= form_for(:guestbook) do |f| %>
<%= f.label :input %>
<%= f.text_field :input %>
<%= f.submit "Sign" %>
<% end %>
And the controller looks like this:
controllers/guest_book_pages_controller.rb
class StaticPagesController < ApplicationController
def home
#userinput = params[:guestbook]["input"]
end
end
Whenever I change the "input" to a symbol :input, the application breaks and gives me a warning that says: undefined method `[]' for nil:NilClass
What is the reason for this? Why can't I use a symbol?
update: Now it won't even work with the string. What is going on?
update#2: It works with both symbols and string. The only problem is that it will not load the first time. If I can get the page to load, then either will work. How can I get the page to load?
Action use to be handle something, and render view.
when you inter home, the home action has be called, and no param posted now.
for your code, home action should just be empty, it just to render the home_page.
your handle code should move to some action like sign_in, whitch handle the form post and you can get the params.
The first time you load the page the params var is not set. It is only when you submit your form back that there are params
Try
#userinput = params[:guestbook]["input"] || ''
which will initialize the #userinput to an empty string if the params is not found
edit:
This will check if the params has the key guestbook first, then will either set the instance var userinput to an empty string or the value of [guestbook][input] if it exsists.
If all else fails, the instance var is initialized to an empty string to prevent an error in your view.
if params.has_key?(:guestbook)
#userinput = params[:guestbook]["input"] || ''
else
#userinput = ''
end

How do I perform inline calculations on two variables within an .erb file?

I have the following .erb view in a Sinatra app:
<% sessions.each do |session| %>
<%= session.balance_beginning %>
<%= session.balance_ending %>
<% end %>
It works as expected, displaying the beginning and ending balances recorded for each session. I would like to calculate the net balances from within the .erb file, but I can't figure out how to do it. I have tried variations of this:
<% sessions.each do |session| %>
<%= session.balance_ending - session.balance_beginning %>
<% end %>
That doesn't work. I receive the following error in Sinatra:
undefined method `-' for nil:NilClass
How do I do what I'm trying to do?
Right #Zabba, in this case I think you would add a method to your Session model so you could call session.net_balance.
Then in your balance_ending and balance_beginning methods you would want to handle nil, either raise an error or return zero if that is valid.

Sorting and manipulating a hash in Ruby

In my rails 3.1 project I have a Book model that has a ID, NAME, and BOOK_ORDER. I am using the ranked-model gem, which for its sorting process creates large numbers in the sorting(:book_order) column. Im looking for some help to create a method to sort all of the Books by the :book_order column, then simplify the :book_order numbers.
So, I have this:
controller
#books = Books.all
view
<% #books.each do |book| %>
<%= book.book_order %>
<% end %>
# book1.book_order => 1231654
# book2.book_order => 9255654
# book3.book_order => 1654
But want this:
view
<% #books.each do |book| %>
<%= book.clean_book_order %>
<% end %>
# book1.clean_book_order => 2
# book2.clean_book_order => 3
# book3.clean_book_order => 1
Additionally, i don’t want to change the database entry, just use its current values to make simpler ones.
Thanks!
UPDATE:
Thanks to nash’s response I was able to find a solution:
In my Book Model I added the clean_book_order method:
class Book < ActiveRecord::Base
include RankedModel
ranks :book_order
def clean_book_order
self.class.where("book_order < ?", book_order).count + 1
end
end
<% #books.each do |book| %>
<%= book.book_order_position %>
<% end %>
EDIT:
Oh, I see. https://github.com/harvesthq/ranked-model/issues/10

Resources