collection_radio_buttons: how do you wrap a tag around each radio button? - form-for

collection_radio_buttons() is defined in the rails 5.1 docs like this:
collection_radio_buttons(
method, collection,
value_method,
text_method,
options = {},
html_options = {}, &block
)
There is no explanation in the docs for what the options argument is. The simple_form docs say that there is an option called item_wrapper_tag.
I've been trying this:
<%= form_for(:an_article, url: "blah") do |f| %>
<%= f.collection_radio_buttons(
:author_id, Author.all,
:id,
:name_with_initial,
{item_wrapper_tag: :div} #<=== HERE *****
)
%>
<% end %>
I've tried every combination of symbols and strings for the key, item_wrapper_tag, and the value, div, and nothing succeeds in wrapping each radio button in a div.
Does anyone know if rails has a similar option as item_wrapper_tag?

Okay, I figured it out:
<%= form_for(:an_article, url: "blah") do |f| %>
<%= f.collection_radio_buttons(
:author_id, Author.all,
:id,
:name_with_initial,
) do |b|
%>
<div>
<%= b.radio_button %>
<%= b.label %>
</div>
<% end %> #collection_radio_buttons do block
<% end %> #form_for do block
radio_button and label are builtin methods for the |b|uilder object:
The argument passed to the block is a special kind of builder for this
collection, which has the ability to generate the label and radio
button for the current item in the collection... Using it, you can
change the label and radio button display order or even use the label
as wrapper...
Additional info:
collection_radio_buttons(object, method,
collection,
value_method, text_method,
options={}, html_options={}, &block)
collection: For each element in collection, a radio button and label tag is created.
value_method: Called on each element in collection, and the return value is assigned to
the value attribute of the radio button.
object.method: If the return value of object.method is equal to the value attribute of a radio button,
the radio button gets a checked="checked" attribute.
text_method: Called on each element in collection, and the return value is used as
the text for the label tag.
options: Unknown purpose.
html_options: Used to specify additional html attributes for the radio button, e.g. {class: 'group1'}
When you use form_for(), the object argument is the object encapsulated by f, so you omit the object argument:
f.collection_radio_buttons(method,
collection,
value_method, text_method,
options={}, html_options={}, &block)
and method is called on this object:
|
V
form_for(:an_article, url: "blah") do |f|

Try using the gem simple_form for your forms. Then the code below should work already.
Add gem simple_form in your Gemfile.
Run bundle install
Run rails generate simple_form:install
Then create a simple_form in your view that would look like this:
<%= simple_form_for #post do |f| %>
<%= f.collection_radio_buttons( :author_id, Author.all, :id, :name_with_initial, item_wrapper_tag: :div) %>
<% end %>
Note: I just followed the form from the collection_radio_buttons from APIDock.
This might do the trick. :)

Related

form_for does not pass the required value when user submits blank form [duplicate]

This question already has answers here:
Rails 4: How do I handle a submitted form where nothing was selected?
(3 answers)
Closed 7 years ago.
I have the following form:
# controller
def edit
#doc = HomeworkDocument.find(params[:id])
end
# view
<%= form_for #doc,
url: student_homework_document_path(student_id: #doc.submitter_id,
id: #doc.id),
html: { multipart: true } do |f| %>
<%= f.label :file1 %>
<%= f.file_field :file1 %>
<%= f.label :file2 %>
<%= f.file_field :file2 %>
<%= f.submit "Submit" %>
When the user submits either one or both of file1 and file2, the form works fine. However, when the user clicks submit without any file, exception is raised:
param is missing or the value is empty: homework_document
due to my strong param specification:
def doc_grader_params
params.require(:homework_document)
.permit(:file1, :file2)
end
The param that gets passed is (notice no homework_document is passed):
Parameters:
{"utf8"=>"✓",
"_method"=>"patch",
"authenticity_token"=>"QJirOW/HQ3sv8AR/yArW6cQ2bmvz0j5D8G6czu45lLA=",
"commit"=>"Submit grading",
"student_id"=>"4",
"id"=>"21"}
Why does this happen and how to to include an (empty) homework_document hash in param even when the user submits blank form?
To include an empty homework_document hash, you have two options:
Assuming you do not want to override the :file1, :file2 attributes if submission is empty, add an empty hidden_field in the form and allow that to pass in via strong parameters, but do virtually nothing to the parameter. Like so:
<%= hidden_field_tag 'homework_document[placeholder]', 'do nothing' %>
def doc_grader_params
params.require(:homework_document)
.permit(:file1, :file2, :placeholder)
end
If you do want to override the attributes (erasing files if empty), place two hidden_fields of name homework_document[file1] and homework_document[file2] before the file inputs and set their value to ''(or whatever defaults you have). Because parameters extraction gets the last occurrence of any repeated key in the query string, this should work.
This approach is similar to the check_box empty submission approach outlined in:
http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-check_box

Rails 4: undefined method `permit' for "xxxx xxxx":String

I have a search model that I hope to use in conjuction with sunspot to handle all searches across different models. I'm stuck before I even have gotne started.
Here is the form...that appears in the header of all the web pages on my site.
<%= simple_form_for #search, :url => searches_path, :method => :post do %>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", class: "btn btn-primary" %>
<% end %>
In my searches_controller
def search_params
params.require(:search).permit(:search)
end
In my Search.rb
attr_accessor :search
When I plug in my name into it I get this error
undefined method `permit' for "simon walsh":String
Parameters:
{"utf8"=>"✓",
"authenticity_token"=>"1Tez0pnMILEciLR6j+li+qSeO4NYBj3XsB6dYG07RymsiNUNSAGI5ztpMiD4JNAtTnqwJYdHTpPBRqGduWHjBw==",
"search"=>"simon walsh",
"commit"=>"Search"}
I am confused. This is clearly a simple error with the way I am posting the params. Any help?
Use this:
def search_params
params.require(:search).permit!
end
Instead of this:
def search_params
params.require(:search).permit(:search)
end
This issue may occur because of string parameter in params["search"], while in controller you are using .permit(:search), or maybe you have an attribute and model name that are the same.

How do I pass form variables from views to controllers in Rails 4?

I'm trying to accept telephone numbers in a simple form and I can't seem to get it to pass the variable through to the controller. The code I have so far is:
view on /users/new.erb:
<%= form_for #user do |f| %>
<%= field_set_tag do %>
<p><%= f.label :phone %><br>
<%= f.text_field :phone%>
<%= f.submit "Submit" %>
<% end %>
<% end %>
and in the controller I have:
def new
#user = User.new
end
def create
#user = User.new(params[:new])
phone = #user.phone
end
Any help would be greatly appreciated. Thanks.
There are a few problems with your code. When you write:
<%= form_for #user %>
All the form fields are sent to the controller in the form of a hash with "user" as the root. Just like
{"user": {"phone": "ENTERED PHONE NUMBER"}}
To access these fields in the controller you need to use the following method:
#phone_number = params[:user][:phone]
One More Important Thing
For security purposes rails does uses Strong Parameters. It means that you can't use the form parameters directly in Active Model for mass assignment like this:
#user = User.new(params[:user])
You need to permit all the fields explicitly for mass assignment. This can be achieved as follows.
def create
#user = User.new(params_user)
#user.save
end
private
def params_user
params.require(:user).permit(:phone)
end
params[:new] just passes the parameter :new to your #user object, but there is no params[:new] parameter because it is not defined in your form. params[:phone] should be passed to '#user' just params if you want all available params that were submitted.
Try
#user = User.new(params) #instead of #user = User.new(params[:new])
#user.phone

Why is my date_field parameter nested inside the label name?

in my controller, I have this:
def index
filter = []
if !params[:paid].blank?
paid = params[:paid]
filter << ["copay_received = '#{paid.to_s}'"]
end
if !params[:junk].blank?
junk = params[:junk][:effective_on]
filter << ["clients.effective_on >= '#{junk.to_s}'"]
end
#unpaids = Appointment.joins(:client).where(filter.join(" AND "))
end
which is based on the (non-accepted) answer to this question.
Here is the form I used on the index page to search it:
<%= form_tag("/", method: "get") do %>
<%= label_tag(:paid, "Search for:") %>
<%= check_box_tag(:paid) %>
<%= date_field(:junk, :effective_on) %>
<%= submit_tag("Search") %>
<% end %>
I finally got my date_field working (as shown with the effective_on parameter).
But my question is why do I have to go an extra layer down into the params hash to get :effective_on while I don't have to do the same thing to reach :paid?
you are using the wrong method. it should be date_field_tag.
the date_field method is supposed to be used with an object form like
form_for #user do |f|
f.date_field :born_on
end

searchresult usin sphinx

i am using sphinx beta and thinking-sphinx to perform search functionality..the search i
wann should search for the word i entered in the database.which is populated with data already.
so in my application Mydoc,i got articlesmodel and controller.. articles is db is populated with data.
i wann to search for the data in articles..so far i ve done with following things but not getting the search result
=> created new search controller
def index
#articles = Article.search params[:search]
end
=> articles.rb(model)
define_index do
indexes name, :sortable => true
indexes description
indexes title, :sortable => true
end
def self.search(search)
ThinkingSphinx::Search
end
=> searches/index.html.erb
<%= form_tag do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "search", :name => nil %>
</p>
<% end %>
BUT WEN I CLICK ON THE SEARCH BUTTON ITS ASKING FOR CREATEACTION ?????
PLEASE COULD U HELP TO GET SEARCH RESULT
Your form is making a POST request to your SearchController, and that is interpreted as a call to the create action. Try using a GET request instead with your form - something like this:
<%= form_tag '', :method => :get do %>