Rails: Adding options to collection_select - ruby-on-rails-3

I am using a collection_select field, but need to prepend the options with some default one, wich does not represent a particular model record and is used to set the appropriet field to NULL. But I just can't find any way to do that.
If you need any more information, don't hasitate to ask.
Using Rails 3.2.3 with standard form helpers.
P.S. I know I can do something like this:
#parents = ['default_name','nil']
#parents << Model.all.map {|item| [item.name,item.id]}
But I think there is a more elegant way.

There is an :include_blank option you can pass to collection_select helper method:
f.collection_select(:author_id, Author.all, :id, :name_with_initial,
:include_blank => "Nothing selected")
There is also a similar option called :prompt, check it out too.

You can probably use select instead :
f.select(:item_id, #items.collect {|p| [ p.name, p.id ] } + ['Or create a new one like','new'], {:include_blank => 'Please select a item'})

Something like this is acceptable in your view?
collection_select :field1, :field2, #models+[Model.new(name: "default_name")], :name, :id

Related

sunspot surely this can be done with some ruby magic?

I need to access my rails model instance from inside the searchable block as indicated below.
class Product
include MongoMapper::Document
include Sunspot::Rails::Searchable
key :field_names, Array
searchable do |ss|
self.field_names.each do |field|
ss.double field[:name] do
field[:value]
end
end
end
end
does anyone know how to do this via Sunspot ?
I have a field_names array on each product instance that is different per product so i need to access it.
Thanks a lot
Rick
you mean this?
def Foo
attr_accessible :id, :title
def fields
['something']
end
searchable do
integer :id
string :title
string :fields, :multiple => true do
self.fields
end
end
end
well inside there, you're inside a different evaluation context (Solr::DSL or something like that). That's to provide the ability to have those keywords like "integer, string". Looks like you're trying to evaluate dynamic attributes/filters .. .. so see my modified response (below)
you mean this?
def Foo
attr_accessible :id, :title
#fields_to_dynamically_add = ['title']
searchable do |s|
s.integer :id
s.string :title
#fields_to_dynamically_add.each do |f|
s.string f.to_sym
end
end
end
PS: have not added fields to searchable blocks dynamically every myself (although the above works)

Using nested attributes to easily select associations in a form

I am trying to create a nested attribute form to create a model which is primarily an association "connector" between two other models. In my case, the models represent books, awards, and the "connector" model book_awards. When I am editing a book, I want to be able to quickly select which awards it has won.
I've been using
http://railscasts.com/episodes/196-nested-model-form-part-1
to help me get started, but I'm afraid I'm pretty much stuck.
Another SO question which seems similar is
accepts_nested_attributes_for with find_or_create? Unfortunately, it's also not quite what I'm doing and I haven't been able to adapt it.
My models look like this. Each model has additional attributes and validations etc, but I've removed them for clarity.
class Book < ActiveRecord::Base
has_many :book_awards
accepts_nested_attributes_for :book_awards, :allow_destroy => true
end
class Award < ActiveRecord::Base
has_many :book_awards
end
class BookAward < ActiveRecord::Base
belongs_to :book, :award
end
In my book controller methods for edit and new, and the failure cases for create and update I have a line #awards = Award.all.
In my view, I would like to see a list of all awards with check boxes next to them. When I submit, I would like to either update, create, or destroy a book_award model. If the check box is selected, I would like to update an existing model or create a new one if it doesn't exist. If the check box isn't selected, then I would like to destroy an existing model or do nothing if the award never existed. I have a partial for book_awards. I'm not sure if the check box selector should be in this partial or not.
I think my check box will be my hook to :_destroy but with its polarity reversed. I think something like this will basically do it:
= f.check_box :_destroy, {}, 0, 1
Currently, I have this in my partial but I'm not sure where it really belongs.
Next comes my view which currently doesn't work, but maybe it will help demonstrate what I'm trying to do. I loop through the awards and use a fields_for to set nested attributes for anything that already exists. It's horribly ugly, but I think it somewhat works. However, I don't really know how to get started with the else case.
= f.label :awards
- #awards.each do |a|
- if f.object.awards && f.object.awards.include?(a)
= f.fields_for :book_awards, f.object.book_award.select{|bas| bas.award == a } do |ba|
= render 'book_awards', :f => ba, :a => a
- else
= fields_for :book_awards do |ba|
= render 'book_awards', :f => ba, :a => a
I would prefer the awards to be listed in the same order each time (my #awards assignment in the controller will probably specify the order) as opposed to listing the existing awards first or last.
I hate to answer my own question, but I finally figured out something which works. The first thing I needed to do was to update the "new" case based on the crazy object which was included in the railscast. Next, I needed to manually set the :child_index. Finally, I needed to manually set the :_destroy check box appropriately.
.field
= f.label :awards
- #awards.each_with_index do |a,i|
- if exists = (f.object.awards && f.object.awards.include?(a))
- new_ba = f.object.book_awards.select{|s| s.award == a}
- else
- new_ba = f.object.class.reflect_on_association(:book_awards).klass.new
= f.fields_for :book_awards, new_ba, :child_index => i do |ba|
= render 'book_awards', :f => ba, :a => a, :existing => exists
My partial looks like this:
.field
= f.check_box :_destroy, {:checked => existing}, 0, 1
= f.label a.name
= f.hidden_field :award_id, :value => a.id
= f.label :year
= f.number_field :year
It's not horribly pretty, but it seems to do exactly what I wanted.

Selected option not working for select

I have this select which works fine, but default the select is empty and doesn't show the selected value (which is filled correctly):
<%= f.select(:relationgroup, options_for_select(#relationgroups), { :selected => #relation.relationgroup, :include_blank => true}) %>
Any idea why? Thanks!
Try it that way:
<%= f.select(
:relationgroup,
options_for_select(#relationgroups, #relation.relationgroup),
:include_blank => true
) %>
Not sure, but maybe it'll work better.
Anyway, assuming Relationgroup is some model with id and name (or any other attribute that you want to be visible in select options) attributes, and you're using default relationgroup_id foreign key in your model you'd better construct your select like that:
<% f.select(
:relationgroup_id,
options_from_collection_for_select(#relationgroups, :id, :name),
:include_blank => true
) %>
It'll choose selected value based on object.relationgroup_id where object is the model you're building form for. See docs for more information.

Rails filtering with acts_as_taggable gem

I am working the acts-as-taggable-on gem and have a question about how to filter down search results based on tags users select. Here's an abridged look at my controller:
class PhotosController < ApplicationController
def index
#photos = Photo.where(["created_at > ? AND is_approved = ?", 1.months.ago, true])
#tags = ["Animals", "Architecture", "Cars", "Flowers", "Food/Drink", "General", "Landscape", "Mountains", "Nature"]
end
def search_by_tag(tag)
#photos = Photo.where('tagged_with LIKE ?', tag)
end
end
Photos/index
<% #tags.each do |tag| %>
<%= link_to tag, {:search_by_tag => tag}, :class => "tag" %>
<% end %>
This lists out all of the tags from the hash #tags defined in index, but clicking them doesn't actually filter anything down. Here's a look at what clicking one of those links produces in the log:
Started GET "/photos?search_by_tag=Animals" for 127.0.0.1 at Sun Oct 09 17:11:09 -0400 2011
Processing by PhotosController#index as HTML
Parameters: {"search_by_tag"=>"Animals"}
SQL (0.5ms) SELECT name FROM sqlite_master WHERE type = 'table' AND NOT name = 'sqlite_sequence'
The result I want is for the page to display only Photos that are tagged_with whichever tag was clicked on. I can't quite figure out how to accomplish this.
(Side-question: I can't seem to find a way to list out all of the tags from the tags table that acts-as-taggable-on generated. Doing something like Photo.tagged_with or Photo.tags doesn't work. I am able to see the "tags" table the gem created, and the entries inside of it; I'm just not really clear how to handle that using this gem)
Any thoughts greatly appreciated.
UPDATE
I've updated my code and am a bit closer.
class PhotosController < ApplicationController
def search_by_tag
#photos = Photo.tagged_with(params[:tag_name])
end
photos/index
<% Photo.tag_counts_on(:tags).map(&:name).each do |tag| %>
<%= link_to tag, {:action => 'search_by_tag', :tag_name => tag}, :class => "tag" %>
<% end %>
I believe this is closer, but still working through this...
You have a number of errors in your code:
Your link_to call is actually calling the index action.
Your search_by_tag method is expecting an argument, where it should be using the params hash to access the parameters passed to it in the web request.
tagged_with is a class method added by acts_as_taggable_on, not a field in your table - therefore you can't use it in the where method like you have done.
Finally, to get all the tag names: Photo.tag_counts_on(:tags_or_whatever_you_tagged_on).map(&:name)
Take a look at the acts_as_taggable_on documentation and you'll see examples of how to use tag_counts_on and tagged_with.
As for the Rails things: http://guides.rubyonrails.org/ http://railsforzombies.org/ and/or http://railscasts.com/

Active Record Querying belong_to

I have the two following models associated:
class Post < ActiveRecord::Base
belongs_to :language
end
class Language < ActiveRecord::Base
has_many :posts
end
From a view I have a link to filter the posts by language:
<div id="english"><%= link_to "English", {:controller => 'posts', :action => 'search_result', :language => "english"} %></div>
The model language has a variable name:string which is the one i am using to make the active record query.
The doubt i have is how i can make this query from the post controller to retrieve the right posts which has a field: language.name == "english".
I tried this:
#posts = Post.all(:conditions => ["language.name = ?", params[:language]])
and also this:
#posts = Post.where(:language.name => params[:language])
Hope i have explained well the issue, i am a quite newbie yet. Ah! i would also know what would it be better in this case to use: "all" or "where" ??.
Thanks a lot in advance.
You need to do a join: http://guides.rubyonrails.org/active_record_querying.html#specifying-conditions-on-the-joined-tables
If I have understood your models/database structure correctly, the ActiveRecord call should looks something like:
Post.joins(:language).where('languages.name' => params[:language])
Hope that helps.
PS. The where call is the preferred method these days.