2 fields in thinking_sphinx search - ruby

I have two fields that I am passing into thinking_sphinx, one is a dropdown, the other a free text.
<%= select :search, params[:search], Category.joins(:posts).select('distinct categories.*').collect {|category| [ category.categoryname,category.categoryname ]}, :include_blank => 'Select a category...' %>
<%= text_field_tag :resume, params[:resume] %>
Its working with just the dropdown, but my syntax seems to be wrong to get the 2nd one to work.
#posts = Post.search :conditions=>{:search=>params[:search]},{:resume=>params[:resume]}
I'm getting : 3: syntax error, unexpected '\n', expecting tASSOC

'conditions' needs to be a hash, you have two hashes. Try this:
#posts = Post.search(:conditions => {:search => params[:search], :resume => params[:resume]})

Related

Ruby: simplest way to convert an array to a hash with named keys?

I have some code in a view script that iterates through an array of arrays:
<% #rows.each do |data| %>
<%= data[0] %>: <%= data[1] %><br>
<% end %>
How can I easily convert each data array to a hash so that I can refer to each item with a key?
<%= data[:name] %>: <%= data[:email] %><br>
You can refer to the arrays with named values like this:
<% #rows.each do |name,email| %>
<%= name %>: <%= email %><br />
<% end %>
This assumes that every member of the #rows array will be the expected two-value array.
#Zach's answer is ok, but answering strictly what you asked for, it can be done this way:
#rows2 = #rows.map { |row| Hash[[:name, :email].zip(row)] }
#Zach and #tokland have supplied two fine answers. Sometimes it's nice to make first class data objects instead of relying on composition of primitive Hashes and Arrays. Struct is handy for this:
irb> EmailTuple = Struct.new :name, :email
=> EmailTuple
irb> rows = [%w{foo foo#example.com}, %w{bar bar#example.com}]
=> [["foo", "foo#example.com"], ["bar", "bar#example.com"]]
irb> rows2 = rows.map{ |row| EmailTuple[ *row ] }
=> [#<struct EmailTuple name="foo", email="foo#example.com">, #<struct EmailTuple name="bar", email="bar#example.com">]
irb> rows2.map{ |tuple| "#{tuple.name} has email #{tuple.email}" }
=> ["foo has email foo#example.com", "bar has email bar#example.com"]

Rails 3 - how to make ternary condition in view?

I have ternary operator and I am trying this ternary operator put into checkbox, but I am still making fault in writing (syntax error)...
So I would like to ask about help, how to do...
CAR: <%= f.check_box :car, :value => 2, ((f.sex == 2) ? (:checked => true) : (:checked => false)) %>
You don't need a ternary operator here. Try this instead:
CAR: <%= f.check_box :car, :value => 2, :checked => (f.sex == 2) %>
Also your problem comes from the fact that in a Hash literal you can't define keys conditionally, so:
{:a => (:b || :c)} is valid
{:b ? (a: => :b) : (:a => :c)} is invalid
<%= f.check_box :car, :value => 2, :checked => f.sex == 2 ? true : false %> will work, but can be shortened to <%= f.check_box :car, :value => 2, :checked => f.sex == 2 %>!

type mismatch: String given - Trying to match strings in ruby

I am using authlogic-connect in Rails. I am using a simple haml template where i dont want to show the authorization providers who are already added.
%h2 My Account
%form.authentication_form{:action => connect_path, :method => :post}
%fieldset
%input{:type => :hidden, :name => :authentication_type, :value => :user}
%legend Add another Oauth or OpenID provider.
.oauth_providers
%ul
- %w(google facebook twitter yahoo).each do |name|
%li.oauth_provider
-unless "{user.authenticated_with}" =~ "{name}"
%img{:src => "/images/icons/#{name}.png"}
%input{:type => :radio, :id => "#{name}_oauth_provider", :name => :oauth_provider, :value => name}
.clearfix
%input.submit{:name => :submit, :type => :submit, :value => "Update"}/
I am encountering the error type mismatch: String. The user.authenticated with returns a string.
def authenticated_with
#authenticated_with ||= self.access_tokens.collect{|t| t.service_name.to_s}
end
What is the possible problem?
Stacktrace:
ActionView::Template::Error (type mismatch: String given):
7: %ul
8: - %w(google facebook twitter yahoo).each do |name|
9: %li.oauth_provider
10: -unless "{user.authenticated_with}" =~ "{name}"
11: %img{:src => "/images/icons/#{name}.png"}
12: %input{:type => :radio, :id => "#{name}_oauth_provider", :name => :oauth_provider, :value => name}
13: .clearfix
app/views/users/edit.html.haml:10:in `=~'
app/views/users/edit.html.haml:10:in `_app_views_users_edit_html_haml___2062853011_2171399360_0'
app/views/users/edit.html.haml:8:in `each'
app/views/users/edit.html.haml:8:in `_app_views_users_edit_html_haml___2062853011_2171399360_0'
Extracted source (around line #10): -- Shows error on line 10
Pass a regular expression as argument to String#=~:
>> string = "el"
>> "hello" =~ /#{string}/
=> 1

Refactor Rails 3 views - move logic to <model>_helper

I would like move the following from my View into the model's associated helper:
<%= link_to_unless params[:aged]=='0', "0", jobs_path(:aged => '0', :sort=>params[:sort],:dir=>params[:dir],:fav=>params[:fav]) %> |
<%= link_to_unless params[:aged]=='30', "30", jobs_path(:aged => '30', :sort=>params[:sort],:dir=>params[:dir],:fav=>params[:fav]) %> |
<%= link_to_unless params[:aged]=='60', "60", jobs_path(:aged => '60', :sort=>params[:sort],:dir=>params[:dir],:fav=>params[:fav]) %> |
<%= link_to_unless params[:aged]=='90', "90", jobs_path(:aged => '90', :sort=>params[:sort],:dir=>params[:dir],:fav=>params[:fav]) %>
I've tried this, but it causes an UNEXPECTED IDENTIFIER error (clearly I need to concatenate the results of the link_to_unless to the '|'):
link_to_unless params[:aged]=='0', "0", users_path(:aged=>'0',:sort=>params[:sort],:dir=>params[:dir],:fav=>params[:fav]) |
link_to_unless params[:aged]=='30', "30", users_path(:aged=>'30',:sort=>params[:sort],:dir=>params[:dir],:fav=>params[:fav]) |
link_to_unless params[:aged]=='60', "60", users_path(:aged=>'60',:sort=>params[:sort],:dir=>params[:dir],:fav=>params[:fav]) |
link_to_unless params[:aged]=='90', "90", users_path(:aged=>'90',:sort=>params[:sort],:dir=>params[:dir],:fav=>params[:fav])
It seems that I need to insert the results these helper methods into the HTML stream, but I'm not certain of the best approach.
Now that Rails 3 includes all helpers all the time (helpers :all) is there a way to instruct a model's view to only use the helper associated with the model? At this point, I'm adding the model's name into the name of the function--for example, 'jobs_sorted_column'.
** edit **
Refactored
jobs_helper:
def posted_filter(bucket)
link_to_unless params[:posted]==bucket, bucket, jobs_path(:posted =>bucket, :starting=>params[:starting],:sort=>params[:sort],:dir=>params[:dir])
end
view:
[ <% ['0','30','60','90'].each do |bucket| %>
<%= posted_filter(bucket) %> |
<% end %> ]
Issues:
Resulting output looks like [ 0 | 30 | 60 | 90 | ]. is there a simple fix to remove the 4th '|'?
It seems like there would be a more elegant way to pass the params to the route, including the one 'over-ridden' value (:posted=>bucket, in my example).
Try using collect and join, something like:
<%= ['0','30','60','90'].collect{ |x| "#{posted_filter(x)}" }.join(' | ') %>
See: Array #collect
You can do it even better:
def posted_filters(*args)
args.collect { |bucket|
link_to_unless(params[:posted]==bucket, bucket, jobs_path(:posted =>bucket, :starting=>params[:starting],:sort=>params[:sort],:dir=>params[:dir]))
}.join(' | ').html_safe
end
And in your view code:
[ <%= posted_filters(0, 30, 60, 90) %> ]

How can I get all the checked items from a submitted form with sinatra's params?

I'm running Sinatra 1.0 with HAML, my form has a number of checkboxes, for example books I like, and you would select all the books you want. The checkbox name is "books".
In sinatra params['books'] there should be an array of all the books that were checked, but it only has the last item that was checked, not an array.
How can I get all the checked items?
HAML:
%form{:action => "/test", :method => 'post'}
%input{:name=>'check',:type=>'checkbox',:value=>'item1'} item 1
%input{:name=>'check',:type=>'checkbox',:value=>'item2'} item 2
%input{:name=>'check',:type=>'checkbox',:value=>'item3'} item 3
%input{:type => "submit", :value => "send", :class => "button"}
Sinatra get method
post '/test' do
puts params['check'] #should be an array but is last item checked
end
Very close, but do not but numbers in the arrays
%form{:action => "/test", :method => 'post'}
%input{:name=>'check[]',:type=>'checkbox',:value=>'item1'} item 1
%input{:name=>'check[]',:type=>'checkbox',:value=>'item2'} item 2
%input{:name=>'check[]',:type=>'checkbox',:value=>'item3'} item 3
Now,
post '/test' do
puts params['check'] #puts an array of what was checked to stdout
end
Wouldn't that output a bunch of checkboxes with the same name? If so, params['check'] is probably getting replaced with each new checkbox.
Try naming each one something different. If you really want it in an array, try hacking the names:
%input{:name=>'check[1]',:type=>'checkbox',:value=>'item1'} item 1
%input{:name=>'check[2]',:type=>'checkbox',:value=>'item2'} item 2
%input{:name=>'check[3]',:type=>'checkbox',:value=>'item3'} item 3
Try
%input{:type => "checkbox", :value => "1", :name => "checkbox[]", :id => "id1"} Chk1
%input{:type => "checkbox", :value => "2", :name => "checkbox[]", :id => "id2"} Chk2
%input{:type => "checkbox", :value => "3", :name => "checkbox[]", :id => "id3"} Chk3
Then in the rails or sinatra
puts params[:checkbox]
Then you can see the checked items.

Resources