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...
Related
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.
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 ...
In my /app/views/institution/_form.html.erb I have
<%= f.textfield :auto_complete_list %>
Which gets its data from /app/models/institution.rb
def auto_complete_list
return self.county.city.name + ' '+ self.county.name
end
But I don't want this to be submitted when the button is pressed.
My current solution is to delete it from params[:institution]
Is there a cleaner approach to removing read-only attributes from submit parameters?
While I agree with daekrist's answer, you can easily keep this out of params[:institution] by using the lower level form helper methods that:
<%= form_for #institution do |f| %>
...
<%= text_field_tag 'auto_complete_list', #institution.auto_complete_list %>
...
<% end %>
So now when the form is submitted, it will be in params[:auto_complete_list] instead of params[:institution][:auto_complete_list].
I suppose, a cleaner approach will be to never put things like this in your forms :)
If you want autocomplete, it would be better to use some js/jquery plugin and attach it to the field you need.
Maybe you want to try token fields, it is well explained here http://railscasts.com/episodes/258-token-fields
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.
I'm faced with the following problem in rails. I have a form to edit/create a new project that may contain 1 to n sub-projects that again can contain 1 to n tasks.
So when I create a new project the controller executes:
#project = Project.new
sub_project = SubProject.new
work = Work.new
sub_project.works << work
#project.sub_projects << sub_project
Having the basic structure I generate the input fields in the view, the form I build up like this:
Project
<% form_for (:project, :url => action_parameter, :id => project) do |form| %>
Subproject
<% fields_for "project[sub_projects][]", sub_project do |subproject_form| %>
Up to here all went well but how do I now define the fields_for the tasks? The following attempt..
<% fields_for "project[sub_projects][works][]", work do |work_form| %>
.. is not the solution as I get the following error from Mongrel:
Conflicting types for parameter
containers. Expected an instance of
Hash, but found an instance of Array.
This can be caused by passing Array
and Hash based paramters
qs[]=value&qs[key]=value.
Why doesn't this work? And how should I tackle my problem?
You need to use a nested model form. Check out this web cast from Ryan Bates.
The reason why my code didn't work was that I forgot to add some extra braces in the work line..
<% fields_for "project[sub_projects][][works][]", work do |work_form| %>
However what I attempted to do does not seem possible with pre Rails 2.3.X. So I updated my App to that version and then used the nested forms which John Drummond suggested.