ruby-on-rails,ruby,ruby-on-rails-4,checkbox,form-helpers , Rails 4: Save Checkbox Results to Serialized Array


Rails 4: Save Checkbox Results to Serialized Array

Question:

Tag: ruby-on-rails,ruby,ruby-on-rails-4,checkbox,form-helpers

I have a Campaign model with a channel column. This channel will store a serialized array of chosen results via checkboxes.

Here's the model..

app/models/campaign.rb

class Campaign < ActiveRecord::Base
    serialize :channels, Array
end

app/controllers/compaigns_controller.rb

class CampaignsController < ApplicationController
      def index
        @campaigns = Campaign.all.order("created_at DESC")
      end

      def new
        @campaign = Campaign.new
      end

      def create
        @campaign = Campaign.new(campaign_params)


        if @campaign.save

            zip = Uploadzip.find(params[:uploadzip_id])
            zip.campaign = @campaign
            zip.save

            flash[:success] = "Campaign Successfully Launched!"
            redirect_to @campaign
        else
            flash[:error] = "There was a problem launching your Campaign."
            redirect_to new_campaign_path
        end
      end

      def show
        @campaign = Campaign.includes(:program, :uploadzip, :channel, :plan, :uploadpdfs).find(params[:id])
      end

  private

      def campaign_params
        params.require(:campaign).permit(:name, :comment, :channel, :plan_id, :program_id, :campaign_id, uploadpdf_ids: [])
      end
end

The part of the form with checkboxes..

views/campaigns/_target.rb

<%= form_for @campaign, url: {action: "create"} do |f| %>

   ...

<label class="right-inline">
   <%= f.label :channel, "Distribution Channel", class: "right-label" %>
</label>

<ul class="channel-list">
    <% ["Folder", "Fax", "Email"].each do |channel| %>

    <li><%= check_box_tag :channel, channel %> <%= channel %>
        <% end %></li>
</ul>

...

<% end %>

I'm having problems saving these results inside the Campaign object.

Any help is highly appreciated.


Answer:

First of all, you mentioned that the column name is channel, but you have used its plural version in Campaign model. Since you are planning to save array of channels in this column, I would suggest you change the name of the column in the database to channels. All the code below assumes that you will change the database column to channels.

Since you are serializing the channels attribute to an Array and your form will send that parameter as an array to the controller, you will need to update your campaign_params method accordingly.

def campaign_params
  params.require(:campaign).permit(:name, :comment, :plan_id, :program_id, :campaign_id, uploadpdf_ids: [], channels: [])
end

Now, the relevant part of your @campaign form should look like this:

<ul class="channels-list">
  <% ["Folder", "Fax", "Email"].each do |channel| %>
    <li><%= check_box_tag "campaign[channels][]", channel, @campaign.channels.include?(channel), id: "campaign_channels_#{channel}" %> <%= channel %></li>
  <% end %>
</ul>

Explanation

First argument in check_box_tag is name attribute of the tag. Second is value attribute. Third is boolean value to tell whether the checkbox will be checked or not when rendered initially. This will be helpful in edit form to show current selections.

Note that I am providing id attribute explicitly. If we don't do that, all three checkboxes will have the same id (derived from their names), which would not be valid HTML because id should not be repeated.

Generated HTML should look like this:

<li><input type="checkbox" name="campaign[channels][]" id="campaign_channels_Folder" value="Folder" /> Folder</li>
<li><input type="checkbox" name="campaign[channels][]" id="campaign_channels_Fax" value="Fax" /> Fax</li>
<li><input type="checkbox" name="campaign[channels][]" id="campaign_channels_Email" value="Email" /> Email</li>

The controller will see channels param as an array of selected values.

This should work both for New and Edit forms.


Related:


Allowing some enabled and disabled option on collection_select


ruby-on-rails,ruby
I am trying to populate a dropdown box on a view that has all the states. This works just fine: <%= f.collection_select :state_id, @states, :id, :name %> Now, I need to make the following: Some states are going to be disabled for choosing, but they still have to appear on...

On rendering from controller, current_page method does not seem to work


ruby-on-rails,ruby,ruby-on-rails-4,model-view-controller
I have a navigation bar included in application.html.erb. Because for some pages, such as the signup page, I need to place additional code inside the navigation bar, I have excluded those pages for showing the navigation bar through application.html.erb and instead included it in their respective view pages. See code...

Keep leading zeroes when converting string to integer


ruby
For no particular reason, I am trying to add a #reverse method to the Integer class: class Integer def reverse self.to_s.reverse.to_i end end puts 1337.reverse # => 7331 puts 1000.reverse # => 1 This works fine except for numbers ending in a 0, as shown when 1000.reverse returns 1 rather...

ActiveAdmin ::Show 4 textbox in active admin using has_many relationship


ruby-on-rails,gem,activeadmin
I have one poll table having with question filed and each question have 4 answer which is has_many relation ship with answer table class Poll < ActiveRecord::Base has_many :answer end My answer model class Answer < ActiveRecord::Base belongs_to :poll, :class_name => "Poll", :foreign_key => "question_id" end My active admin form...

Is it possible to have two callbacks in around_destroy in rails?


ruby-on-rails,activerecord,callback
Although this can be accomplished as follows: class Model < ActiveRecord::Base around_destroy :callback def callback puts 'callback1 before yield' puts 'callback2 before yield' yield puts 'callback1 after yield' puts 'callback2 after yield' end end But I wish to do the following: class Model < ActiveRecord::Base around_destroy :callback1, :callback2 def callback1...

For loop with flexible stop variable


ruby
I need to write a loop for x in (1..y) where the y variable can be changed somehow. How can I do that? For example: for x in (1..y/x) But it does not work. ...

Ruby- get a xml node value


ruby,xml
can someone help me in extracting the node value for the element "Name". Type 1: I am able to extract the "name" value for the below xml by using the below code <Element> <Details> <ID>20367</ID> <Name>Ram</Name> <Name>Sam</Name> </Details> </Element> doc = Nokogiri::XML(response.body) values = doc.xpath('//Name').map{ |node| node.text}.join ',' puts values...

Ruby access words in string


ruby
I don't understand the best method to access a certain word by it's number in a string. I tried using [] to access a word but instead it returns letter. puts s # => I went for a walk puts s[3] # => w ...

Ruby on Rails - Help Adding Badges to Application


ruby-on-rails,ruby,rest,activerecord,one-to-many
I'm creating a rails application that is a backend for a mobile application. The backend is implemented with a RESTful web API. Currently I am trying to add gamification to the platform through the use of badges that can be earned by the user. Right now the badges are tied...

Rails Association Guidance [on hold]


ruby-on-rails,ruby,ruby-on-rails-4,ruby-on-rails-3.2
I am new to rails 4. I have gone through lots of tutorials and trying to solve below scenario. But still no success. Can anybody point me in the right direction. How to handle associations for below scenario. Scenario: 1. Patient can have many surgeries. 2. Surgery has two types...

Active Record association links, but can't assign values


ruby-on-rails
I'm setting up permissions for each user to determine what access they have to certain data. I have a user model and a permission model that is set up with a has_many and belongs_to association like so: app/models/permission.rb class Permission < ActiveRecord::Base has_many :users end app/models/user.rb class User < ActiveRecord::Base...

Split an array into slices, with groupings


arrays,ruby,enumerable
I've got some Ruby code here, that works, but I'm certain I'm not doing it as efficiently as I can. I have an Array of Objects, along this line: [ { name: "foo1", location: "new york" }, { name: "foo2", location: "new york" }, { name: "foo3", location: "new york"...

How to pivot array into another array in Ruby


arrays,ruby,csv
I have a multidimensional array like this one : myArray = [["Alaska","Rain","3"],["Alaska","Snow","4"],["Alabama","Snow","2"],["Alabama","Hail","1"]] I would like to end up with CSV output like this. State,Snow,Rain,Hail Alaska,4,3,nil Alabama,2,nil,1 I know that to get this outputted to CSV the way I want it I have to have output array like this: outputArray =[["State","Snow","Rain","Hail"],["Alaska",4,3,nil],["Alabama",2,nil,1]]...

How to find a record from database by using find_by with two fields?


ruby-on-rails
I want to find a record from database in ruby on rails by using find_by with two fields. How can I accomplish it?

Stack level too deep because recursion


ruby-on-rails,ruby,ruby-on-rails-4,twitter
I have a model named Tweet. The columns of the Tweet model are: -id -content -user_id -picture -group -original_tweet_id Every tweet can have one or multiple retweets. The relation happens with the help of original_tweet_id. All the tweets have original_tweet_id nil , whilst the retweets contain the id of the...

Heroku rake db:migrate failing - uninitialized constant


ruby-on-rails,ruby,heroku
My app is working fine locally and my push to Heroku was successful. But, when I run heroku run rake db:migrate, I get the following error: NameError: uninitialized constant AddWeightToExercises Here is the failed migration: class AddWeightToExercise < ActiveRecord::Migration def change add_column :exercises, :weight, :float end end edit: Thanks for...

Loop until i get correct user


ruby,redis
I have users stored in Redis and want to be able to call only certain subsets from a set, if i don't get the correct user back i want to put it back in the set and then try again until i get one of the desired users @redis =...

Javascript not executing when using link_to


javascript,jquery,ruby-on-rails
I have couple javascript functions that attaching action to buttons in controller view some/index. I navigate to some/index using link_to method. But when i'm using link_to method, buttons has no attached javascript actions (in some/index view). When i try open some/index directly from my browser, buttons have all attached actions...

Rails: Posting from a form to a M:M table


ruby-on-rails,activerecord
On the group index page I display a listing of group discussions and a form to create a new discussion. class Group < ActiveRecord::Base has_many :discussions end class Discussion < ActiveRecord::Base belongs_to :user belongs_to :group end Controller: class DiscussionsController < ApplicationController def index @group = Group.find(params[:group_id]) @discussion = current_user.discussions.build({group_id: @group.id})...

What is Rack::Utils.multipart_part_limit within Rails and what function does it perform?


ruby-on-rails,ruby,rack,multipart
Rack::Utils.multipart_part_limit is set to 128 by default. What purpose does the value have and what effect does it have within the Rails system?...

Rails shared controller actions


ruby-on-rails,ruby,ruby-on-rails-4
I am having trouble building a controller concern. I would like the concern to extend the classes available actions. Given I have the controller 'SamplesController' class SamplesController < ApplicationController include Searchable perform_search_on(Sample, handle: [ClothingType, Company, Collection, Color]) end I include the module 'Searchable' module Searchable extend ActiveSupport::Concern module ClassMethods def...

Get the actual value of a boolean attribute


ruby,page-object-gem,rspec3,rspec-expectations
I have the span: <span disabled="disabled">Edit Member</span> When I try to get the value of the disabled attribute: page.in_iframe(:id => 'MembersAreaFrame') do |frame| expect(page.span_element(:xpath => "//span[text()='Edit Member']", :frame => frame).attribute('disabled')).to eq("disabled") end I get: expected: "disabled" got: "true" How do I get the value of specified attribute instead of a...

Rails basic auth not working properly


ruby-on-rails,ruby,authentication
I am building a small API that uses basic authentication. What I have done, is that a user can generate a username and password, that could be used to authenticate to the API. However I have discovered that it is not working 100% as intended. It appears that a request...

Make instance variable accessible through hash in Ruby


ruby-on-rails,ruby,ruby-on-rails-4,activerecord
In Rails, ActiveRecord objects, attributes are accessible via method as well as through Hash. Example: user = User.first # Assuming User to be inheriting from ActiveRecord::Base user.name # Accessing attribute 'name' via method user[:name] # Attribute 'name' is accessible via hash as well How to make instance variables accessible through...

Showing and editing has_many objects in Rails


ruby-on-rails,ruby-on-rails-4
I'm trying to do something that I imagine to be very basic, but I'm very new to Rails and am not sure what sure what I'm doing wrong. I've gone through several tutorials and searched for an answer and can't find what the issue is. Would appreciate any help! I've...

Same enum values for multiple columns


ruby-on-rails,ruby,enums
I need to do something like this: class PlanetEdge < ActiveRecord::Base enum :first_planet [ :earth, :mars, :jupiter] enum :second_planet [ :earth, :mars, :jupiter] end Where my table is a table of edges but each vertex is an integer. However, it seems the abvove is not possible in rails. What might...

How to send a mail by postfix mail server with rails?


ruby-on-rails,email,mailer
On my local host, I followed this article made a mail server and it works well. https://www.digitalocean.com/community/tutorials/how-to-install-postfix-on-centos-6 I want to develop a mailer feature with rails framework. Here are my settings: # mailer config.action_mailer.default_url_options = { :host => 'example.com' } config.action_mailer.delivery_method = :smtp config.action_mailer.smtp_settings = { address: 'localhost', port: 25,...

Routes work in Development But not in Production


ruby-on-rails,routes
Weird Error. I have some routes that work perfectly during development but once i deploy and try to access them it comes up with page does not Exist error I have the following routes.rb file: TransportUnl::Application.routes.draw do resources :trucks resources :shipments do collection do get :autocomplete_location_cs end end devise_for :users...

Ruby boolean logic: some amount of variables are true


ruby
Let say I have 3 variables: a, b, c. How can I check that just zero or one of them is true?...

Can Rails deal with DB uniqueness without index?


mysql,ruby-on-rails,rdbms
I see add_index ~ unique: true statement in schema.rband think uniqueness is constraint for table, not for index.Using index is one of way realizing uniqueness, Programmer should not designate to the RDBMS "how" and index quicken searching but take costs inserting. In fact, is there another way to keep uniqueness...

RoR Tutorial Chapter 3 - Guard detects changes but doesn't fully execute tests


ruby-on-rails,railstutorial.org,minitest,guard
I'm currently following the book and the video and in the video, Hartl runs a guardfile so that it automatically runs tests after any changes have been made. So in the videos when he presses return whilst in guard mode, it says: 17:35:31 - INFO - Running: test/controllers/static_pages_controller_test.rb followed by...

How to pass array in rails 4 strong parameters


ruby-on-rails,arrays
I have to pass a array of food_item_ids in my order_controller. Every order will have many food_items. How can I pass these food_items_id as an array in strong parameters. orders_controller.rb def create @order = Order.new(order_params) if @order.save render :json, @order, status:201, location: [:api, @order] else render :json, { errors: @order.errors...

Mongoid HABTM relationships across embedded documents


ruby-on-rails,ruby-on-rails-4,mongoid,embedded-documents
I'm trying to create a Mongoid N-N reference association between two embedded documents in Rails 4 however I'm finding it difficult to get my head round how this is done. I started by adding the HABTM association to the relevant models below (Track and Option) but of course I'm getting...

Heroku RAM not increasing with upgraded dynos


ruby-on-rails,ruby,ruby-on-rails-3,memory,heroku
I have a massive function i have been calling manually through the heroku rails console. I have been receiving the error rapid fire in my logs: 2015-06-22T14:56:42.940517+00:00 heroku[run.9877]: Process running mem=575M(112.4%) 2015-06-22T14:56:42.940517+00:00 heroku[run.9877]: Error R14 (Memory quota exceeded) A 1X dyno is suppose to have 512 MB of RAM. I...

If statement for search field in Rails


jquery,ruby-on-rails,search,if-statement
I have a blog site and recently added a search bar for visitors to browse through blog posts. When used, all of the posts go away in the directory and only those which return via the search appear. In order to show the general directory and view all, I would...

Ruby: How to copy the multidimensional array in new array?


ruby-on-rails,arrays,ruby,multidimensional-array
seating_arrangement [ [:first, :second, :none], [:first, :none, :second], [:second, :second, :first], ] I need to copy this array into new array. I tried to do it by following code: class Simulator @@current_state def initialize(seating_arrangement) @@current_state = seating_arrangement.dup end But whenever I am making any changes to seating_arrangement current_state changes automatically....

Get X days out of an Array


ruby,ruby-on-rails-4
I have an array filled with Datetime objects: [Mon, 22 Jun 2015, Tue, 23 Jun 2015, Wed, 24 Jun 2015, Thu, 25 Jun 2015, Fri, 26 Jun 2015, Sat, 27 Jun 2015, Sun, 28 Jun 2015] I know how to select what I want from the array ex: week.select{|x|x.monday? ||...