What is the proper use of the check_box form helper? - ruby-on-rails

I have two models - Client & Topic, with a HABTM relationship between them.
I am trying to generate a series of checkboxes of the topics, on the Client form partial.
This is what I am doing:
<% Topic.all.each do |topic| %>
<% checked = #client.topics.include?(topic) %>
<%= f.label(:name, topic.name) %> <%= f.check_box #topics, topic.id %>
<% end %>
This is the error I get:
undefined method `merge' for 1:Fixnum
I know one solution is to use check_box_tag, but that forces me to do the record updating of the associations manually.
So I would rather use the form_helper for the checkbox tag. The docs are a bit confusing to me.
How can I get this to work with f.check_box.
Thanks.

The code confuses me. What #topics contains? If it's a collection of of Topic then why you are directly accessing Topic model in the view? It would be:
#topics.each.do
rather than you
Topic.all.each
Moreover, you are using #topics as collection inside a loop. How check_box will generate checkbox from a collection?
Please look at the following things:
accepts_nested_attributes_for. you will need this to set in Client model in addition to Client has_many Topic association
fields_for Otherwise, rails will not have any idea that you want to update topic model from this same form.
Check this screencasts to get an idea how you can make it work

For whatever reason, the form helper doesn't work with check_box.
So, this is the code that works:
<%= check_box_tag "client[topic_ids][]", topic.id, checked %>
According to other answers for similar questions, the helper f.check_box is model bound and the value supplied to the checkbox is implicit from the model on the form. The issue is, I can't figure out how to get the implicit value of the form_helper to produce the correct tag - i.e. client[topic_ids][], so I have had to resort to check_box_tag.

Related

Rails custom form generator - radio button not in response parameters unless it has a value

Ok, I've been digging around and haven't found an answer to this. I have a pretty complex custom rails form generator application that renders pages, sections, & surveys (forms) from a database.
It does validation server side (haven't finished the javascript yet and want both types), and I have it working for all types of form input objects, except for radio buttons. Because I can't get it to submit radio buttons to show up in params when they are not checked. As opposed to just looking for radio buttons outside of the params, I'd like to find a way to check them in my response loop (if possible).
I've seen this suggestion of binding it to the model to make sure it validates, but my questions are unique and therefore I don't have a model object I'm binding it to.
My form is declared in one partial:
<%= form_tag take_surveys_path, :id => "take_surveys_new", :method => :post do %>
and my code for generating the radio button (part of a partial that looks at a question type field):
<% when 'Radio Button' %>
<% question.answers.each do |answer| %>
<%= radio_button "response[#{question.id}]content", question.question_text, answer.value %>
<%=answer.value%>
<br />
<% end %>
<% end %>
I iterate over params in my "take_survey_controller" and then check each question to see if it's valid, which includes regex and required validation based on some attributes set in my question object:
params[:response].each do |question_id, answer|
#find my questions and answers, call
if item.valid?
#do a bunch of saving and stuff...
end
end
but this never gets called for radio buttons because empty radio buttons don't post to the params.
Any suggestions or help? Happy to share more code if needed.
What you're looking for is a way to set a default value for your radio buttons. Checkboxes do this by default, but in this instance it doesn't look like it's happening for your radio buttons.
Try this:
<%= hidden_field "response[#{question.id}]content", question.question_text %>
<%= radio_button "response[#{question.id}]content", question.question_text, answer.value %>
It sounds like part of your validation should include checking input params. If a radio button isn't selected it won't submit a value, thus you need to have a list of question ids and ensure each question was submitted before moving into your params response loop.
array_of_question_ids.each do |id|
handle_missing_question(id) unless params[:response][id]
end
params[:response].each ...

How would I add a method to ActiveView::Helpers::FormHelper to be used with form_for?

I am currently making a plugin, and I would like to add a method to ActiveView::Helpers::FormHelper, Essentially, the plugin is a helper that will convert checkbox input into bitwise flags so when you do actions like new and update, you can continue to pass in a params hash, and my plugin will pull out the checkbox data and convert it into a single number representing the flag state. Anyway, I want to be able to do something like this:
<% form_for #person do |f| %>
<%= f.check_boxes_for_flags %>
<% end %>
Which would create checkboxes in the HTML and then set them accordingly to the flags. I know how to add an instance method to ActiveView::Helpers::FormHelper, but I'm not sure how to access #person from this method. Any ideas?
Why wouldn't you use:
<%= f.check_boxes_for_flags :country %>
That way you can create your extension similar to how the ActiveView helpers work.
Take a look at how check_box_tag in the rails source code gets the name from the model. Try to follow the conventions set forth by the framework, it makes things easier for you and those who will maintain your code after you.

Send an extra parameter through a form in rails 3

Is there a way to send an extra parameter through a form in rails 3?
For example:
<%= form_for #post do |f| %>
<%= f.hidden_field :extraparam, :value => "22" %>
<% end %>
but lets say :extraparam isn't part of the post model..
I have an unknown attribute error in the create method of the controller when I try this, any ideas?
(I want to use the param value itself in the controller for some extra logic)
Call hidden_field_tag directly. See: http://api.rubyonrails.org/classes/ActionView/Helpers/FormTagHelper.html#method-i-hidden_field_tag
These helpers exist for all the major form field types, and are handy when you need to go beyond your model's methods.
The following worked for me in passing extra parameters from the view back to the controller that were a part of my model and not part of my model.
<%= hidden_field_tag :extraparam, value %>
Example usage
<%= hidden_field_tag :name, "John Smith" %>
Ya Paul is right. Hidden_field is associated with your model whereas the extra _tag fields are not. I'm not sure of your needs but It's generally recommended in the RoR community to avoid passing a ton of hidden_fields like you might do in a php application.
Ive seen some code where ids were getting passed around in hidden fields which rails takes care on its own if you know the best practices and take full advantage of the framework. Of course I'm just saying this as general info as there are sometimes better ways at accomplishing the same functionality. Good luck on your apps.

Nested models, forms and date_select FormHelper integration

I have followed Ryan Bates tutorial on nested models. Several of my nested models have dates associated with them. In my migrations, they are actually the type "Date."
Some things I have tried and problems I've run into
date_select - can handle the form object prefix, but not nested models attributes
select_year - doesn't work with form object
a regular select populated with the year by using (Time.now.year - 100)..(Time.now.year) and overriding the attr accessor start_date and end_date to take the value in the select to form a date and passing that back. works on create only, not on update
changing the data type of the field to string and using a regular select populated with the year by using using (Time.now.year - 100)..(Time.now.year) works, but on edit, it won't repopulate the select with the current information
Any ideas or hints would be helpful.
Edit: before_save seems to be more promising but for some reason, the value is nil coming into before save but is visible in the log dump.
Edit 2: Interestingly, this only seems to be a problem on 'update', not on 'create'.
This is the solution:
<% new_or_existing = task.new_record? ? 'new' : 'existing' %>
<% prefix = "project[#{new_or_existing}_task_attributes][]" %>
<% fields_for prefix, task do |t| -%>
<%= t.date_select(:start_date, :index => task.id || nil) %>
<% end -%>
Here's the explanation of why it works:
http://agilerails.wordpress.com/2009/03/11/date_select-time_select-doesnt-work-with-auto_prefix-object/
I'd seriously hope that this works for date_select as well:
http://jeffperrin.com/2009/06/04/rails-nested-forms-and-collection_select/
Maybe this would work with the formtastic gem...

Rails: Fields_for without a scope?

Is there a way to use fields_for with in a form without having a scope?
For example:
<% fields_for "user[]" do |x|
<%= x.text_field :name %>
<% end %>
Without the user model being loaded in memory?
I got it working using territory[user][][name], but I would like to keep it in ERB.
I think the answer would be 'no', since those form_for and fields_for would try to determine default value from that given instance variable.
However, I think if you want to lower memory usage from loading that model, you might try to create a mock-up model to return nil values, and create a instance object from that one instead.
is there any specific reason you need to use form_for specifically? Its really designed to be used with an instantiated model object.
Alternatively, why don't you just use the regular form helper tags. You can define it as follows:
<%form_tag :my_form do %>
<%= text_field_tag :foo, :bar %>
<%end%>
You may want to check the documentation for action view to see how it all works.

Resources