Simple form - Keep radio buttons checked when edit - ruby

I have few radio buttons; the issue is that when I edit the instance, the radio buttons are not checked anymore (however they have been saved in db when I created it). I would like that the radio buttons the user previoulsy checked, to be still checked when edit.
_form.html.slim
.cov-pick-row.w-row
- #inspiration_images.each do |img|
- next if img.image.path.nil?
.w-col.w-col-2.w-col-small-4.w-col-tiny-6
label
INPUT[type="checkbox" name="cover[inspiration_image_ids][]" id='cover_inspiration_image_ids' value="#{img.id}" class="hidden"]
.image-cov-pick
= cl_image_tag(img.image.path, height: 190, class: 'img-to-pick', data: { ix: "cover-pick" }).html_safe

Set checked: true for which it should be check. Ex. assume you have db column check_status where you store checked value then use checked: img.check_status.
From your sample code as much as I understand that you are saving image id on inspiration_image_ids so use can use inspiration_image_ids.include?(img.id)

Use checked: [#your ids]
Example :
create_table "mymodel", force: :cascade do |t|
t.string "interest_ids", default: [], array: true
end
# _form
<%= simple_form_for(#mymodel) do |f| %>
<%= f.input :interests_ids,
as: :check_boxes, # Display check_boxes
collection: Interest.all, # Search into ids collection
value_method: :id, # Save only the ids
checked: #mymodel.interests_ids, # keep and check the old values
input_html: { multiple: true }
%>
...

Related

ActiveAdmin Generic Form Partial

I have the following form for uploading PDFs:
f.inputs 'PDF' do
f.has_many :pdfs, allow_destroy: true do |pdf_f|
pdf_f.semantic_errors
pdf_f.input :name
pdf_f.input :description
pdf_f.input :enabled
pdf_f.input :link, label: 'file', as: :file
end
end
And a way to display the file:
li do
div "name: #{pdf.name}"
div "filename: #{pdf.link.path.split('/').last}"
div raw "description: <br> #{pdf.description}"
div "enabled: #{pdf.enabled ? "yes" : "no"}"
end
Pdf is a polymorphic object thus can appear on several models.
How do I create a generic shard partial for each of them that can then be re-used across ActiveAdmin so I don't have to recreate them every time?
Bear in mind the second one I expect to iterate over it by passing it in as a collection:
For the form answer is to place the form in a partial that resides in:
app/views/active_admin/base/_pdf_form.erb
and then render it like this:
render partial: 'pdf_form', locals: {f: f}
For the display parital you should place the partial at:
app/views/active_admin/base/_pdf.erb
and then render it like this:
render partial: 'pdf', collection: event.pdfs
The partial name needs to be in quotes otherwise rails won't look for it active_admin/base.

ajax-datatables-rails How to add buttons in ajax response

My problem is that I don't know how to add different buttons that remain in a condition using the gem for server side processing ajax-datatables-rails. For example before trying to do sever side processing I had this in my view.
<% if current_user.sales_manager? || current_user.admin? %>
<td>
<%= link_to t('.destroy', :default => t("helpers.links.destroy")),
bill_sale_path(bill_sale),
:method => :delete %>
</td>
<% end %>
and following the tutorial in the main page of the gem, in bill_sale_datatable.rb I have this.
def data
records.map do |record|
[
link_to('Show', bill_sale_path(record), class: 'btn-xs btn-link'),
record.customer.name,
record.seller.name,
l(record.date_sold, format: :short),
record.payment_type.name,
record.payed,
number_to_currency(record.total),
CONDITION AND BUTTON HERE
]
end
end
Then, how do I use the server side processing to provide different buttons that belongs to an if condition?
While I haven't used the gem, I have used datatables with Rails and this is what I did:
Store the button as a variable before the array and then just call the variable in the array.
records.map do |record|
record_button = ''
record_button = button_to('A', button1_path) if condition1
record_button = button_to('B', button2_path) if condition2
record_button = button_to('C', button3_path) if condition3
record_button = button_to('D', button4_path) if condition4
[
link_to('Show', bill_sale_path(record), class: 'btn-xs btn-link'),
record.customer.name,
record.seller.name,
l(record.date_sold, format: :short),
record.payment_type.name,
record.payed,
number_to_currency(record.total),
record_button
]
end
You could also use a case statement if that suited your needs.
Make sure you add
def_delegator :#view, :button_to
To the top of your file as per:
https://github.com/jbox-web/ajax-datatables-rails#using-view-helpers

optional date field with simple_form

I am using simple_form to generate date input like so:
= f.input :date_of_death
However, it always pre-populates with the current date.
How can I have it come up "blank" and allow the user to easily NOT enter a date?
Thanks!
There are a couple of ways to do this while still keeping the form split into dropdowns for Y/M/D.
= f.input :date_of_death, include_blank: true
Or if you want the first option to have text use prompt.
= f.input :date_of_death, prompt: "Choose Wisely"
Simplest way that I have found
f.input :date_of_death, as: :string
It will turn the input into a blank input field. You will have to parse the string as a date in your controller.
Use include_blank
= f.input :fecha_at, include_blank: true, start_year: Date.today.year - 90, end_year: Date.today.year

Ruby rails - submit_tag / button_tag switch/toggle between names

How do I switch/toggle names between two or more names on single button?
For one condition I want the name to be as "Add", and for the other condition I want the name changed to "Remove". and switch between them based on status at the back end.
<%= button_tag "Add" , :id => "add_or_remove_button", :onclick => "javascript:add_or_remove_button()"%>
I can do "Add/Remove", and clicking on the same button will still do the job. But I want it specific.
Since you didn't say where the condition comes from, I will assume it is in an instance variable called #button_condition
You can do this (I haven't tested it)
button_tag(:type => 'button',:onclick => "javascript:add_or_remove_button()", :id => "add_or_remove_button") do
if #button_condition == X
"Add"
else
"Remove"
end
end
Take a look at: Button tag documentation

Add readable field descriptions to ActiveRecord models

I'd like to add descriptions to ActiveRecord model fields to serve as basic instructions / examples for each of the fields. Basically model metadata. I can then display these in the UI (next to the fields on a form etc.)
The way I'm planning to do it is simply create a static hashtable inside the model with the field name as the key and description as the value. I.e.
FIELD_DESCRIPTIONS = {
'category' => 'Select the category it should appear within.',
'title' => 'The title should be a short but descriptive summary.',
'description' => 'Please enter a full description.'
}
etc.
Then I would create a a basic form helper that would wrap these explanations inside of a span (initially hidden and shown via jQuery) so they could be instatiated via f.field_description(:title) or something along those lines.
Anyone have any better ideas? I'd like to keep this field metadata in the model since many views could use the same information, and I also think it's nice to have descriptions within the model when you're going back to look at the code (like how DataMapper can be used right within the model to specify fields).
To give you a little more detail on what I've already done (and it works fine) here's the code. I think there has to be a prettier way of expressing these descriptions in the model, so let me know if you have any ideas.
In model:
FIELD_DESCRIPTIONS = {
'category' => 'Select the category it should appear within.',
'title' => 'The title should be a short but descriptive summary.',
'description' => 'Please enter a full description.'
}
def self.describe_field(field)
FIELD_DESCRIPTIONS[field]
end
In application_helper.rb
def field_helper(form, field)
"<span class='field_helper'>#{form.object.class.describe_field(field)}</span>"
end
In view:
<%= field_helper(f, 'title') %>
This will produce the desired output:
<span class='field_helper'>The title should be a short but descriptive summary.</span>
UPDATE:
Ok So this is the final code I'm using based on the accepted answer.
File: /config/initializers/describe_attr.rb
if defined?(ActiveRecord)
# let's us add attribute descriptions to each AR model
class ActiveRecord::Base
def self.describe_attr(*params)
attrs = params.shift
unless attrs.nil?
case attrs
when Hash
##attr_descriptions = attrs
when Symbol
return ##attr_descriptions[attrs]
end
end
##attr_descriptions ||= {}
end
end
end
File: /app/models/project.rb
describe_attr(
:category => 'Select the category the project should appear within.',
:title => 'The title should be a short but descriptive summary of the project.',
:description => 'Describe the project in detail.',
:image => 'Upload an image for the project.'
)
File: /app/helpers/application_helper.rb
# assumes you have a style defined for attr_description
def describe_attr(form, attribute)
"<span class='attr_description'>#{form.object.class.describe_attr(attribute)}</span>"
end
File: /app/views/projects/_form.html.erb
<%= describe_attr(f, :title) %>
The hash is a reasonable simple solution, but if you're on rails 2.2 or higher you might want to try the internationalization api to do this. This would also put you in a good place if you ever wanted to add translations.
Check out the i18n guide for details, but basically you would create a config/locales/en.yml that includes your column names like:
en:
labels:
category: Select the category it should appear within.
Then in your view:
<%= t('labels.category') %>
The namespace is your call of course. Also check out section 4.1.4 for a neat way to separate translations based on your current view template.
If you want to patch ActiveRecord, then you can do something like:
# Add this at the bottom of enviroment.rb
class ActiveRecord::Base
def self.field_description(*params)
attrs = params.shift
unless attrs.nil?
case attrs
when Hash
##field_description = attrs
when Symbol
return ##field_description[attrs]
end
end
##field_description ||= {}
end
end
And inside your model you can add this line like a macro:
class Product < ActiveRecord::Base
field_description :category => 'Select the category it should appear within.',:title => 'The title should be a short but descriptive summary.',:description => 'Please enter a full description.'
end
To get the value
Product.field_description : title
You can mix your solution with the label helper itself:
f.label :title, f.describe(:title)
And in your model:
FIELD_DESCRIPTIONS = {
:category => 'Select the category it should appear within.',
:title => 'The title should be a short but descriptive summary.',
:description => 'Please enter a full description.'
}
def describe(:field)
self.class::FIELD_DESCRIPTIONS[field]
end
Be sure to check out formtastic, which includes support for internationalized (or not) field labels as per matschaffer's answer.
http://github.com/justinfrench/formtastic/

Resources