Formtastic pre-check few checkboxes - ruby-on-rails

I'm trying to manually tell formtastic to check a few checkboxes. #some_array currently has an element called checked which exists for each member.
= f.input :cboxes, label: "CBoxes", as: :check_boxes,
collection: #some_array.map { |a| [a[:name], a[:id]] }
I've tried to set the input_html to { checked: 'checked' } (How to pre-check checkboxes in formtastic) but this checks all checkboxes, not just the select few that I want.
The contents of #some_array are coming via an API, and I can't change the database structure (Ruby on Rails + Formtastic: Not checking checkboxes for multiple checked answers)
Suggestions?

If you are editing an ActiveModel, you don't need to "manually select checkboxes".
Let's consider a simple example with a single User model which has fields username and roles. Roles field is a string column, which Rails serializes as an Array. It might also be has_many relation to other ActiveModel, but we assume it's an Array for simplicity.
User is defined in user.rb:
class User < ActiveRecord::Base
serialize :roles, Array
end
Now you can "assign manually" desired roles to User in your controller:
#user = User.new(username: 'dimakura', roles: ['admin', 'editor'])
and define form in your view:
<%= semantic_form_for #user do |f| %>
<%= f.input :username %>
<%= f.input :roles, as: :check_boxes, collection: ['owner', 'admin', 'editor', 'viewer'] %>
<% end %>
In given example only "admin" and "editor" roles will be pre-selected in form. The "owner" and "viewer" role won't be selected.
Update Official documentation states:
Formtastic, much like Rails, is very ActiveRecord-centric.
But actually it's not a big challenge to create ActiveRecord-compatible model yourself. An example of doing this can be found in this blog post.

Related

Using Role Model and simple_forms to assign roles

First off, I am using Devise, Cancan, Role Model, and simple_form. Everything seems to work with permissions and whatnot. What I can't seem to do is create a form so that I can assign roles to Users.
Here is what I have so far:
<%= simple_form_for(#profile.user) do |f| %>
<%= f.input :roles_mask, as: :check_boxes, collection: User.valid_roles, :checked => [ 'member' , true] %>
<%= f.button :submit %>
This shows the check boxes properly, and the last part flags one as true. I'm not sure how to get it to flag the roles that are supposed to be flagged. I chose one at random for testing Also, if I send it to update, nothing seems to happen. I updated like I normally would limiting my params to just the roles_mask variable.
def update
if #user.update(params.require(:user).permit(:roles_mask))
flash[:notice] = "Permissions updated."
redirect_to profile_path(#user.profile_id)
else
render 'edit'
end
I have no clue what I am doing wrong. Even if I could just get them to update. Not showing the current roles isn't a huge deal.
You don't need to directly access roles_mask property, just assign roles property with the array of roles. Example:
= f.input :roles, collection: User.valid_roles, as: :check_boxes, checked: #user.roles, label_method: proc {|l| User.human_attribute_name(l) }
And don't forget to permit that form value for strong parameters:
params.require(:user).permit(roles: [])

Pass a parameter to the new action in Active Admin

I have two related models, Bunny has_many BunnyData (which belongs_to Bunny). From the show page of a particular Bunny (in Active Admin), I want to create a link to make a related BunnyData. I've tried a few different ways, with no success, and am currently trying this:
sidebar :data, :only => :show do
link_to 'New Data', new_admin_bunny_datum(:bunny_id => bunny.id)
end
The link being generated ends up as something like:
.../admin/bunny_data/new?bunny_id=5
But when you go to that page, the dropdown for Bunny is set to the blank default as opposed to showing the name of Bunny with ID 5.
Thanks in advance.
Rails namespaces form fields to the data model, in this case BunnyData. For the form to be pre-filled, any fields provided must also include the namespace. As an example:
ActiveAdmin.register Post do
form do |f|
f.inputs "Post Details" do
f.input :user
f.input :title
f.input :content
end
f.actions
end
end
The fields can be pre-filled by passing a hash to the path helper.
link_to 'New Post', new_admin_post_path(:post => { :user_id => user.id })
Which would generate the following path and set the form field.
/admin/posts/new?post[user_id]=5
In the case of BunnyData, it might be slightly different due to the singular and plural forms of datum. But that can be verified by inspecting the generated HTML to find the name attribute of the inputs.

Rails 3 + ActiveAdmin: How to make a user save two resources dependent on each other?

I have 2 models, one is called Hotel and one is called HotelInfo.
When a user saves an Hotel resource in ActiveAdmin I want it to force the user to fill out the form for HotelInfo as well before it can be saved.
If possible, how can I do this?
Here is an example code that how to add two models together in active admin.
form do |f|
f.inputs "Hotel" do
f.input :name
end
f.inputs "Hotel Information", :for => [:hotel_info, f.object.hotel_info || HotelInfo.new] do |hotel_info_form|
hotel_info_form.input :telephone
end
f.buttons
end
You could use a fields_for helper to have both resources on the same form. Make sure your parent object has accepts_nested_attributes_for :hotelinfo set.

How do I generate a bunch of checkboxes from a collection?

I have two models User and Category that have a HABTM association.
I would like to generate checkboxes from a collection of Category items on my view, and have them associated with the current_user.
How do I do that?
Thanks.
P.S. I know that I can do the equivalent for a dropdown menu with options_from_collection_for_select. I also know that Rails has a checkbox_tag helper. But not quite sure how to do both of them. I know I can just do it manually with an each loop or something, but am wondering if there is something native to Rails 3 that I am missing.
Did you check out formtastic or simple_form
They have helpers to write your forms more easily, also to handle simple associations.
E.g. in simple_form you can just write
= simple_form_for #user do
= f.association :categories, :as => :check_boxes
In form_tastic you would write
= simple_form_for #user do
= f.input :categories, :as => :check_boxes
Hope this helps.
You can use a collection_select and feed it the options. Assuming you have a form builder wrapped around a user instance, you can do something like this:
form_for current_user do |f|
f.collection_select(
:category_ids, # the param key, so params[:user][:category_ids]
f.object.categories, # the collection of items in the list
:id, # option value
:name # option string
)
end
You may want to pass the :multiple => true option on the end if needed.

declarative_authorization problem with creating new user

I used declarative_authorization for my app and had problem with creating new user.
my User model code:
class User < ActiveRecord::Base
ROLE_TYPES = ["admin", "user", "guest"]
validates_inclusion_of :roles, :in => ROLE_TYPES
def role_symbols
#role_symbols ||= (roles || []).map{|r| r.to_sym}
end
my view code:
<% form_for(#user) do |f| %>
...
<p>
<%= f.label :roles %><br />
<%= f.select :roles, User::ROLE_TYPES, :prompt => "Select a role" %>
</p>
<%= f.submit 'Add User' %>
<% end %>
every time i tried to create a new user and select the role from the drop-down list, the view complaint:
Roles is not included in the list
from the output of the script/server, i can see the roles was actually set:
"user"=>{"name"=>"kc", "password_confirmation"=>"kc", "roles"=>"guest", "password"=>"kc", "email"=>"kc#one.com"}
can anyone tell me what's wrong? why the validation wont' pass?
Is it possible that you've got attr_accessible attributes on the user to prevent mass assignment of certain attributes and that :roles isn't in there? You would get a warning about this in your logs though. The default User class generated by restful_authentication does include the attr_accessible call so it may be there without you having added it if you are using that authentication plugin too.
Is there definitely a roles attribute of the right type for users? It looks like you're expecting roles to be a single string from your form but in the code from declarative_authorization you've got (roles || []).map which suggests that that part of the code at least is expecting an array of roles.

Resources