A set of mutually-exclusive attributes need to be selected, thus via a radio_button.
<% #finitures.each do |finiture| %>
<%= f.radio_button :finitura_stampa, finiture %> <%= finiture.nome %><br />
<% end %>
However, NIL is an allowed value.
One way to handle this is to create a dummy record that tries to be invisible, but that's not very clean.
A better way would be to have a radio button with a label 'None' that sets the attribute to NIL.
I have not found a way to do this.
The only real satisfactory answer is 'use collection_select with a prompt'.
Creating a table entry for nil creates all sorts of consequences which are useless costs.
I understand the point about 'radio means selecting something', however in some contexts (multiple variables with non-array values) may benefit from a UI perspective of having radio buttons: users can more easily compare different values simultaneously without activating one-by-one each pullDown menu.
Related
First of all, I've done a fair amount of looking around, and while questions get around answers, I have a problem I think is somewhat unique. I have a list of checkboxes generated with the following code:
<% for student in Student.find(:all) %>
<div>
<%= check_box_tag "user[student_ids][]", student.id, current_user.students.include (student) %>
<%= student.name %>
</div>
<% end %>
After clicking the 'update' button at the bottom, I need each of the checked boxes to be placed into an array. I then plan on iterating over the array and doing some work on each of the checked names. I am having a hard time, however, with the process of getting these names all into an array. I really am not sure which of the standard web actions this kind of work should be (i.e, post, get, etc.), so I don't know how to set up a route. Even if I could set up a route to a controller, how would I get the checked students into an array of Student objects?
Thanks ahead of time for your help!
The full answer to your question depends on a variety of things, for example, what you are trying to do with the submitted array, etc (which would determine whether POST, GET, PUT or DELETE should be used.) Without knowing more information with respect to your code base, if you throw the following code into a form_for in one of your controller's already restful routes, you should be able to see the array of checked names:
<%= current_user.students.include(student).each do |student| %>
<div>
<%= check_box_tag "student_names[]", student.name %> <%= label_tag student.name %>
</div>
<% end %>
Then, when the user hits submit, the params hash will show student_names = [].
And make sure your attributes are accessible as needed.
On a side note, check out Railscasts pro episode from last week. Pretty much exactly explains what you are trying to do. It's a subscription service, though.
I managed to solve my problem in a less-than-satisfying way. Here is the code I ended up using:
current_user.students.delete_all
if(params.has_key? :user)
params[:user][:student_ids].each do |i|
current_user.students<<(Student.find(i))
end
end
Because the number of students I'm managing is not ever larger than 100, this operation isn't as bad as it looks. I'm deleting all of the associations already present, and then cycling through all passed parameters. I then find the student object with the passed parameter id and add it to the current_user's User-Student join table.
I hope this helps someone down the line!
I am trying to pass an extra variable, that determines whether or not the user has clicked on a particular checkbox, and this variable is not a part of my model. I want to make it so on the controller update function, it can have access to this variable, and see what it was set to. I have seen some other stack overflow answers for this type of problem, and it is generally suggested to do something using hidden_field_tag, something like this:
<% hidden_field_tag "blah", params[:test] %>
or
<% hidden_field_tag :example, "test" %>
When trying this, I did a params.inspect and could not find the "test" param variable, using both of the above options. Should I be trying to retrieve this hidden field tag in a different way? Will it be available in the update request to the controller? If not, does anyone know some way this is possible?
Open to any suggestions,
--Anthony
You would either do it like this
<%= hidden_field_tag 'test' , 'blah' %>
or you could do this
<%= hidden_field_tag :whatever_you_want , 'blah', {:name=>'test'}
You had the name and value reversed in your post. The really important thing is to make sure the form element has the name you want to show up in the params hash. The second example would generate the element with id='whatever_you_want' name='test'.
This is long so I hope you'll bear with me...
I have a model called Update with two subclasses, MrUpdate and TriggeredUpdate. Using single-table inheritance, added type field as a string to Update.
In my view I'm checking which type it is to decide what to display. I assumed since type is a string, I should do
<% if #update.type == 'MrUpdate' %>
This failed, i.e., it evaluated to false when the update was an MrUpdate. I noticed that at this point, #update.type.type is Class. OK, whatever, thought I, so I changed it to:
<% if #update.type == MrUpdate %>
and it worked, i.e., the comparison evaluated to true when the update was an MrUdpate. Then I did it again lower down in my view and it failed again (i.e., it evaluated to false when the update was an MrUpdate.)
Turns out the culprit is a couple of <%= link_to ... %> calls I use and make into buttons with jQuery. If I put this code in my view:
<br>
<%= #update.type.type %><br>
<%= #update.type %><br>
<%= link_to 'New Note', new_note_path(:update_id => #update.id), :class => "ui-button" %>
<br>
<%= #update.type.type %><br>
<%= #update.type %><br>
What I see is:
Class
MrUpdate
(the New Note button)
String
MrUpdate
It's changing from a class to a string! So what the heck am I doing wrong or missing here? Why should a link_to do that? First I'm not clear why it's not a string in the first place, but then really confused as to why it would change...?!? Any help or explanation would be helpful. I can just code it one way at the top and another way at the bottom, but that way madness lies. I need to understand why this is happening.
I figured out what the issue is here. Thanks to fl00r for pointing the way.
Yes, type is a reserved in Ruby 1.8.7 which tells you the class of the object you call it from. But it's also true that it is the name of the field used in Rails to indicate single-table inheriance and to store the name of the class of each instance of the subclass.
So I naively tried to access the value of the type field using #update.type. But what this was doing at the top of the view was calling the type method of the Object class in Ruby. For whatever reason, after the link_to calls, it was then access the value of the type field of the updates table.
While trying to figure this out I called #update.type in the Rails console and saw this message: "warning: Object#type is deprecated; use Object#class". Finally it registered what I was doing. When I changed my calls to:
<% if #update.class == MrUpdate %>
everything works as expected. I never saw a call to determine the type in any of the pages I found via Google about STI. This despite the fact that they all recommended using only one controller, wherein sometimes you must need to determine the class of the instance you have.
So, dumb mistake--pilot error. But maybe this will help someone else who gets tripped up on this.
I search for a working solution for a rather simple problem, but could not find a good explanation.
What I currently have (working) is an index view which contains:
a form to enter a new element and
a paginated list of existing elements (using will_paginate).
For the list I am interested in only part of the data, thus I am trying to add a form with filter options and I would like to store the forms content in a cookie (which should be replaced with an per user object stored in the database, but i do not have users yet). What I cannot figure out is how to get the values from the form stored in a cookie (and vice versa) and how to use it together with will_paginated.
What I currently tried to do as a first step is to create an #filter object in my controller and adding the filter form for this object, setting the form options to use the index controller again. This leads to selected filter parameters passed in the params hash to the index controller (visible in the url). But this solution has some drawbacks. first the filters are gone as soon as I change the view (e.g. by creating a new element) and second the #filter object should be the cookie instead.
Here is the code I have so far:
View-partial for filter:
<%= form_for(#filter, :url => {:action => "index"}, :html => {:method => :get}) do |f| %>
<div class="field">
<%= f.label :german %><br />
<%= f.check_box :german %>
</div>
<div class="actions">
<%= f.submit "Filter" %>
</div>
<% end %>
Controller:
def index
#word = Word.new
#filter = Word.new(params[:word])
#words = Word.paginate(:page => params[:page]).order('word')
# ....
Can anybody help me? How is such a functionality (filtering results) done in other applications?
So the answer to the question is, use a where clause to include only the matching records in your result.
#words = Word
.where("german = ?", params[:word][:german] != 0")
.order('word')
.paginate(:page => params[:page])
This is a new Rails syntax called Active Relation (AREL for short), which should generally replace the older find and find_by methods. It has several benefits that can improve performance, notably that the SQL it executes (which you can see in your logs) only occurs when it is referenced, not when it is declared. This give you neat ways of defining partial relations (even as named scopes) that you can build up to create simpler statements that combine together.
The order of the various clauses doesn't matter -- AREL will generate the same SQL, but generally I like to follow the order of the underlying SQL,
where
joins
group
order
limit
offset
(limit and offset are handled in your case by the pagination tool).
I just discovered the rails-settings gem and now I need to make an admin page that lets me edit the setting values. How would I make a settings controller with an edit view that can change these dynamic app wide settings?
I haven't used this gem but it seems like it should be fairly straight forward. Since it uses a database backed model, you would simply create a controller as normal:
rails g controller Settings
From here you would define your index action to gather all your individual settings for display in the view:
def index
#settings = Settings.all
end
Then in the view you can setup a loop to display them:
<% #settings.each do |setting| %>
<%= setting.var %> = <%= setting.value %>
<% end %>
As far as editing ... this might be a bit tricky since by default rails would expect you to submit only one setting at a time to edit. You could do it this way but unless you implement the edit with ajax it might be tedious and non-intuitive.
Another way would be to set up your update method to accept all the individual settings at once, loop through and update each one with new values. It might look something like this:
// The /settings route would need to be setup manually since it is without an id (the default)
<%= form_tag("/settings", :method => "put") do %>
<% #settings.each do |setting| %>
<%= label_tag(setting.var, setting.var) %>
<%= text_field_tag(setting.var, :value => setting.value) %>
<% end %>
<%= submit_tag("Save Changes") %>
<% end %>
This should output all of the settings (given they have been assigned to the #settings variable) with the var name as the label and the current value as the text field value. Assuming that the routing is setup, when you submit this form the action that receives it should all the new settings in the params variable. Then you can do something like this in the action:
def update
params.each_pair do |setting, value|
eval("Settings.#{setting} = #{value}")
end
redirect_to settings_path, :notice => 'Settings updated' # Redirect to the settings index
end
This may not be the best way depending on how often you edit the settings and how many settings you have...but this is a possible solution.
I was looking for some suggestions for this and found another answer to this that is very simple and elegant, for anyone looking for this later. It just sets up dynamic accessors in your model, allowing your form to have settings fields just like your normal attributes. An example can be found in the original answer:
How to create a form for the rails-settings plugin