Monday, July 25, 2016

Ruby on Rails - Create a form with Multiple instances of the same model | Fixed issues

Ruby on Rails - Create a form with Multiple instances of the same model | Fixed issues


Ruby on Rails - Create a form with Multiple instances of the same model

Posted: 25 Jul 2016 08:15 AM PDT

I have a model, namely "bank_accounts", which contains many users

I want to use a form to list out all users (while the first name is editable), so that one click of "submit" can gather all users' first name.

-@bank_accounts.each do |account|    =form_for account do |f|      =f.text_field :first_name  

The code above gives something like

    <form class="edit_bank_accounts" id="edit_bank_account_1" action="/bank_account/1" accept-charset="UTF-8" method="post">      <input type="text" value="123" name="bank_account[first_name]" id="bank_account_first_name"/>      </form>  <form class="edit_bank_accounts" id="edit_bank_account_2" action="/bank_account/2" accept-charset="UTF-8" method="post">      <input type="text" value="456" name="bank_account[first_name]" id="bank_account_first_name"/>      </form>  

But what I want is

<form class="edit_bank_accounts" id="edit_bank_account" action="/bank_account" accept-charset="UTF-8" method="post">      <input type="text" value="123" name="bank_account[1][first_name]" id="bank_account_first_name"/>  <input type="text" value="456" name="bank_account[2][first_name]" id="bank_account_first_name"/>      </form>  

How to generate bank_account[id][first_name] for the form in Ruby on Rails?

Thanks.

rails4-autocomplete gem using mulitple options. Getting extra data from search with multiple => true

Posted: 25 Jul 2016 08:10 AM PDT

I have a table where I am searching by name of payer, put then using the payer_id in the input b/c I am then using it in an API call. My problem is I can't get multiple => true option with gem to work while using :extra_data. I either get extra_data option to work or the multiple => true option to work. If anyone has experience with this, help is much appreciated. Code is below:

controller:

      autocomplete :payer, :payer_name, :full => true, :limit => 100, :extra_data => [:payer_id]  

view:

    <div class:"form-group ">        <%= label_tag :payer_id, "Payer Id", class: "control-label" %>        <%= autocomplete_field_tag "payer_id", "",  autocomplete_payer_payer_name_insurances_path, :update_elements => {:payer_id => '#payer_id'}, 'data-delimiter' => ',', :multiple => true %>      </div>  

I've tried reordering them a number different ways, nothing seems to work. Multiple true seems to be the dominate option.

What is the accepted way for admin-only tasks

Posted: 25 Jul 2016 08:20 AM PDT

I'm not using devise for learning purposes. I want admins to be able to access an admin-only page.

I've created an admin boolean with a default state of false. So I can check if someone is an admin by something like current_user.admin?.

Is doing something like

 before_action :admin_check, only: :show    def admin_check        redirect_to(root_url) unless current_user.admin?   end  

safe in terms of security?

Dividing up an index params into multiple pages

Posted: 25 Jul 2016 07:55 AM PDT

I have a list of records that I have displayed on an index page. (they are displayed in a table form). Because there are a number of them I am trying to divide them up to about 30 records per page. I've created a search params functionality with the index displayed beneath it.

The problem that I am having is that I am having trouble getting more than one page to render on my list. As of right now I have about 150 records. However I only have one page listed with only 30 records on it and am not able to sort through them. Would anybody have any idea what I could be missing?

Here is the segment in my code where this gets addresssed.

  def search_params      default_index_params.merge(params.fetch(:record_collection, {})).with_indifferent_access    end      def default_index_params      {        per: 30,        page: 1,        sort_by: "created_at",        sort_direction: "desc",        customer_id: 0       }    end  

In my view, I do have a little bit of coffee-script that plays a role in the table itself. I don't know if it is the root of my problem, but I have it here as well.

:coffeescript    $('#record_table').dataTable      aaSorting: [[1, 'asc']]      bPaginate: false      bFilter: false,      aoColumns:[null, null, null, null, null, { bSortable: false }, null, { bSortable: false }]  

My record collection is used for defining the params, i don't think that it is useful for this problem. (but could certainly post if needed)

Thanks in advance to anybody who is able to help figure out what is going on with this.

Create new instance of Campaign in every iteration

Posted: 25 Jul 2016 08:07 AM PDT

I am working on functionality whereby a table is displayed with records, each with radio buttons Reject and Approve. A user selects the appropriate radio button and presses process. Control is passed to process_campaigns. From here it breaks down the data and analyses each record's status. If it is approved it redirects to approve block and same with reject.

The following parameters are passed:

Parameters: {"utf8"=>"✓", "authenticity_token"=>"9TCExvCmDahAWGQloPdaRkSowbBaxZGwZnRa8sbNkWM=", "campaign"=>{"2"=>{"start_date"=>"2016-07-18 15:43:00", "end_date"=>"2016-10-15 12:20:00", "merchant_revenue"=>"10", "status"=>"Approved", "notes"=>""}, "1"=>{"start_date"=>"2016-07-15 12:20:00", "end_date"=>"", "merchant_revenue"=>"10", "status"=>"Approved", "notes"=>""}}, "Commit"=>"Process"}    def process_campaign    authorize! :operator, current_user.operator     params[:campaign].each do |key, value|      if value[:status] == "Approved"        redirect_to approve_operator_campaign_path(key), :id => key, :start_date => value[:start_date], :revenue_mode => value[:revenue_model], :end_date =>  value[:end_date], :active => true, :status => 307 and return       elsif value[:status] == "Rejected"        redirect_to reject_operator_campaign_path(key), campaign_name: key, notes: value[:notes], :status => 307 and return       end    end    redirect_to operator_campaigns_path, flash: { notice: "Campaigns have been processed."}  end    def reject    authorize! :operator, current_user.operator    params[:campaign].each do |key, value|      if value[:status] = "Rejected"        @campaign = Campaign.active.where(id: key, operator_id: current_user.operator_id).last!        @campaign.data.merge!({:notes=>value[:notes]})        @campaign.status = "Rejected"        @campaign.save(validate: false)      end    end  end    def approve    @campaign = Campaign.find(params[:id])    params[:campaign].each do |key, value|      if value[:status] = "Approved"        @applied_campaign = AppliedCampaign.new(:campaign_id => key, :start_date => value[:start_date]||Time.now, :end_date =>  value[:end_date], :active => true)      end    end  end  

The problem is when control is passed to approve or reject the entire campaign string is passed with both records contained within whereas I want to seperate each record and pass it individually. Can anyone indicate why the entire campaign string is being passed?

How to get records by month

Posted: 25 Jul 2016 08:20 AM PDT

I have tried several solutions but the only one close enough to what i want is this

Sale.all.group("DATE_TRUNC('month', created_at)").count  

but it returns something like this

{2016-07-01 00:00:00 UTC=>19, 2016-04-01 00:00:00 UTC=>70}

is there something that can do this format?

[month,number of sales] ??

using postgres db.

Integration Tests: Filling Autocomple Dropdown in Rails_Admin using Capybara for

Posted: 25 Jul 2016 07:47 AM PDT

In my rails app, I'm using rails_admin. I want to fill a relationship. Say, a Post belongs to an Author. I want to set the author. rails_admin uses autocomplete form for selection of this data, i.e. xhr. How do I select value and submit this data using capybara. Normal select doesn't work here.

I'm assuming I need to take following actions

  1. Click on carrot icon,
  2. Select first value from dropdown

Or is there some other approach to fill such data, i.e execute script etc. But how do I do that?

Thanks in advance,

RSpec throws a NoMethodError, but method works in the app

Posted: 25 Jul 2016 08:13 AM PDT

I have a method 'current_balance' defined in invoice.rb:

  belongs_to :purchase    has_many :payments, dependent: :destroy      validates :number, presence: true    validates :currency, format: {with: /\A[A-Z]+\z/, message: "Please enter the 3 letter currency code in CAPS."}    validates :total_due, presence: true    validates :due_date, format: {with: /\d{4}-\d{2}-\d{2}/, message: "format must be YYYY-MM-DD"}    validates :status, presence: true      def current_balance     self.current_balance = (self.total_due - self.payments.sum(:amount_paid))    end  

The model spec, invoices_spec.rb contains:

require "spec_helper"    describe Invoice, '#current_balance' do    it "calculates the current balance of an invoice" do      invoice = FactoryGirl.create(:invoice, total_due: 200)      invoice.payments << FactoryGirl.create(:payment, amount_paid: 100)      invoice.payments << FactoryGirl.create(:payment, amount_paid: 50)      expect(invoice.current_balance).to eq(50)    end  end    describe Invoice do    before(:all) { @invoice = FactoryGirl.build(:invoice) }      it "has a valid factory" do        expect(FactoryGirl.create(:invoice)).to be_valid      end        it "is invalid without a number" do        invoice = Invoice.new(number: nil)        expect(invoice).to_not be_valid      end        it "is invalid without a currency" do        invoice = Invoice.new(currency: nil)        expect(invoice).to_not be_valid      end        it "is invalid without a total_due" do        invoice = Invoice.new(total_due: nil)        expect(invoice).to_not be_valid      end        it "is invalid without a due_date" do        invoice = Invoice.new(due_date: nil)        expect(invoice).to_not be_valid      end        it "is invalid without a status" do        invoice = Invoice.new(status: nil)        expect(invoice).to_not be_valid      end    end  

The method works perfectly and calculates the current balance of an invoice when I run the app. When I run the model spec, however, I get an error.

The '#current_balance' & 'it has a valid factory' examples pass, the rest fail with the same error.

Failure/Error: expect(invoice).to_not be_valid  NoMethodError:   undefined method `-' for nil:NilClass  

What am I doing wrong?

Fake Class for Development Environment

Posted: 25 Jul 2016 08:17 AM PDT

I have a service that runs on the production machine that I access through a service class in my app.

Because of licensing costs, I'd like to fake that service for my test and development environments.

How can I load a different class definition depending on Environment in my rails app?

ActiveRecord query from an array of hash

Posted: 25 Jul 2016 07:40 AM PDT

I have an array of hash.

eg) array_of_hash = [ { id: 20, name: 'John' }, { id: 30, name: 'Doe'} ]  

I would like to get records which match all the criteria in a particular hash. So the query I want to get executed is

SELECT persons.* FROM persons WHERE persons.id = 20 AND persons.name = 'John' OR persons.id = 30 AND persons.name = 'Doe'   

What is the best way to construct this query from an array of hash?

YAML File has a syntax error, but it looks like it has the same format as another one that is working?

Posted: 25 Jul 2016 07:49 AM PDT

I have two YAML files with similar formats, however one is running and the other is not running when I run integration tests on my rails app.

Here is the first YAML file which doesn't work:

prince_edward_island:    name: 'prince edward island'    country: 'Canada'  

nova_scotia: name: 'nova scotia' country: 'Canada'

newfoundland:    name: 'newfoundland'    country: 'Canada'    new_brunswick:    name: 'new brunswick'    country: 'Canada'    quebec:    name: 'quebec'    country: 'Canada'    manitoba:    name: 'manitoba'    country: 'Canada'    alberta:    name: 'alberta'    country: 'Canada'    ontario:    name: 'ontario'    country: 'Canada'    british_columbia: 'Canada'    name: 'british columbia'    country: 'Canada'    saskatchewan: 'Canada'    name: 'saskatchewan'    country: 'Canada'  

Here is the second YAML file which does work:

student_advisor_message:    body: 'This is a message'    subject: 'Subject!'    user: student_advisor    manager_message:    body: 'This is a message'    subject: 'Subject!'    user: manager    read_manager_message:    body: 'This is a message'    subject: 'Subject!'    user: manager    agent_manager_message:    body: 'This is a message'    subject: 'Subject!'    user: agent_manager    message_for_jack:    body: 'This is a message'    subject: 'Subject!'    user: manager    message_for_jack_sent:    body: 'This is a sent message'    subject: 'Sent Subject!'    user: manager    message_for_jack_trash:    body: 'This is a trashed message'    subject: 'Trash Subject!'    user: manager  

The error is:

ERROR:    while parsing a block mapping    in "<unicode string>", line 1, column 1:      prince_edward_island:      ^  expected <block end>, but found '<block mapping start>'    in "<unicode string>", line 34, column 3:        name: 'british columbia'  

Can someone explain the difference I am missing between the two? For both I use spaces, not tabs.

Using find_or_initialize on Rails 5

Posted: 25 Jul 2016 08:10 AM PDT

I'm playing with Rails 5's find_or_initialize in my Blog app that has Posts and Categories entered into input text fields.

Post model

# == Schema Information  #  # Table name: posts  #  #  id           :integer          not null, primary key  #  title        :string           default(""), not null  #  body         :text             default(""), not null  #  created_at   :datetime         not null  #  updated_at   :datetime         not null  #  category_id  :integer      class Post < ApplicationRecord    validates :title, :body, :category, presence: true      has_one :category    accepts_nested_attributes_for :category  end  

Category model

# == Schema Information  #  # Table name: category  #  #  id         :integer          not null, primary key  #  name       :string           default(""), not null  #  created_at :datetime         not null  #  updated_at :datetime         not null    class Category < ApplicationRecord    validates :name, presence: true    validates :name, length: { in: 3..80 }      has_many :posts  end  

In the console I can get the following to work:

post = Post.new(title: "Hello Stack Overflow", body: "How are you today?")  post.category = Category.find_or_initialize_by(name: "Greetings")  post.save    post.last  => #<Post:0x007fd34fa21a23   id: 42,   title: "Hello Stack Overflow",   body: "How are you today?",   created_at: Mon, 25 Jul 2016 12:56:39 UTC +00:00,   updated_at: Mon, 25 Jul 2016 12:56:39 UTC +00:00,   category_id: 3>  

The Post form looks like this:

<%= form_for @post do |f| %>    <fieldset>      <%= f.label "Title" %>      <%= f.text_field :body %>    </fieldset>      <fieldset>      <%= f.fields_for :category do |category_fields|         <%= f.label "Category" %>         <%= category_fields.text_field :name %>      <% end %>    </fieldset>     <% end %>  

My trouble is trying to get what is entered in the category fields_for input into the Post model to use the find_or_initialize.

I tried the following:

class Post < ApplicationRecord    before_save :generate_category?      has_one :category    accepts_nested_attributes_for :category      private       def generate_category?       self.category = Category.find_or_initialize_by(name: name)     end  end  

This fails and I'm getting an NameError error:

NameError in PostController#create  undefined local variable or method `name' for #<Listing:0x007fc3d9b48a48>  

My question is:

  1. How do I access the category attributes-is there a way to access the nested_attributes in the model?
  2. Am I using the right callback with before_save
  3. Should I be handling this in the controller somehow?

Any tips on how I can code this would be much appreciated.

RSpec when to use it should respond_to

Posted: 25 Jul 2016 08:01 AM PDT

I have two models linked together by a belongs_to and has_many relationship as shown below.

Class OtherModel < ActiveRecord::Base    belongs_to my_model  end    class MyModel < ActiveRecord::Base    has_many other_models  end  

I now have the respective tests to verify that they have the correct relationship shown below.

RSpec.describe MyModel, type: :model do    it {should have_many(:other_models)}    it {should respond_to(:other_models)}  end    RSpec.describe OtherModel, type: :model do    it {should have_many(:my_model)}    it {should respond_to(:my_model)}  end  

For this relationship, is the respond_to required, and if so why? What does it check for that the have_many does not already check for? If the respond_to is not needed in this case, when is an appropriate time to use it? From my current understanding have_many already verifies that the field exists, and thus obsoletes the respond_to check.

Defining a chained ruby method definition similar to rails

Posted: 25 Jul 2016 08:21 AM PDT

I am studying the Rails documentation. Within the associations documentation they specify method definitions with a chain on them, like this:

Project#portfolio.nil?

This seemed odd to me. It would appear that there is an instance method definition that has a chained method on it. For example: It appears thatProject#portfolio.nil? would define an instance method that would look like this:

class Project < ActiveRecord::Base      def portfolio.nil?      ...    end  end  

I have never seen instance methods defined like this before: where a chain is specified within the actual instance method definition. I attempted to replicate it with straight ruby and I couldn't get it to work.

class Dog    def speak     puts "woof woof"    end      def speak.fetch      puts "go get the ball!"    end  end  

However this does not work. There is a NameError

NameError: undefined local variable or method `speak' for Dog:Class

If it did work: then I would try Dog.new.speak.fetch. I am not sure what it would return. Maybe it would return:

=> woof woof!  => go get the ball!  

Question: Is it even possible to somehow define instance method definitions with chains on them like this? If not: how does rails do it? Using Project#portfolio.nil? as an example: how does Rails go about defining #portfolio.nil? ?

Capybara - NameError: uninitialized constant Capybara::TimeoutError

Posted: 25 Jul 2016 07:07 AM PDT

I am creating integration tests for my rails application.

The application I am working to is a little slow. In my test, I execute a certain action within the website (a "saving" - which reloads in the end the page) and the following capybara action runs before the page is actually reloaded.

I cannot use "sleep (seconds)" as this freezes the "reloading" itself.

So I wanted to give a try to this github idea: https://gist.github.com/metaskills/1172519

but I get the following error:

NameError: uninitialized constant Capybara::TimeoutError

Can someone tell me why I get this error and what does it mean?

Newbie. I can not deal with Gemset

Posted: 25 Jul 2016 07:53 AM PDT

so in default have Ruby 2.3.1 and Ruby on Rails 5.0.0 Ruby 2.0.0 is still installed I created a new gemset called test_app went to him, I switched to Ruby 2.0.0 and installed Ruby on Rails 4.0.0 Now when you go to there default missing Ruby on Rails 5.0.0 and at the same time remove all the gems in addition to default I do something wrong or did not understand? Is every gemsete should not remain your order whether there are gems, etc. Thanks to Google translator

NameError: Uninitialized Constant though model is located under /app/models

Posted: 25 Jul 2016 07:27 AM PDT

Currently, I am writing a class file called Ticket.rb in order to create a Scumblr workflow. I have this file saved under /app/models, but when I try to execute the below line of code, I get a NameError: uninitialized constant Ticket:

ticket = Ticket.create(summary=>"Test ticket")  

The above line of code is executed on the rails console.

The code for the class file (/app/models/Ticket.rb) is below:

class Ticket < ActiveRecord::Base     acts_as_workflowable  end  

The error that I get looks like this on the console:

[5] pry(main)> ticket = Ticket.create(summary=>"Test ticket")  NameError: uninitialized constant Ticket  from (pry):5:in `__pry__'  

Also, I am following the tutorial that can be found here to set up the workflow: https://github.com/Netflix/Workflowable/wiki

I'm a complete newbie when it comes to Ruby on Rails and I've made sure that I followed the tutorial exactly until the Ticket.create line of code, but I'm not sure if there is something that is not mentioned in the tutorial and that's where I'm going wrong. I haven't seen anything that would address this issue on Stack Overflow and I could really use some help. Thanks in advance!

Heroku does not show 'git remote heroku added'

Posted: 25 Jul 2016 06:31 AM PDT

I setup my project doing the following

  • git init
  • added a server.js
  • git add .
  • git commit -am "first commit"

Then I login to my heroku using heroku login

And run heroku create which does the following:

C:\Users\git\web-server>heroku create  Creating app... done, floating-scrubland-78193  https://floating-scrubland-78193.herokuapp.com/ | https://git.heroku.com/floating-scrubland-78193.git  

As you can see, there is no git remote heroku added at the end. WHY?

Then when I try to do git push heroku master, it does not work:

C:\Users\git\web-server>git push heroku master  remote: !       No such app as calm-bastion-70777.  fatal: repository 'https://git.heroku.com/calm-bastion-70777.git/' not found  

Ruby unit test assert match case insensitive strings

Posted: 25 Jul 2016 06:28 AM PDT

In a Ruby unit test, how do I assert that a string matches another string even though the casing might be different? I want to avoid sanitizing the two strings to match incase I need to come back and do some investigation but at the same time they are the same outcomes.

e.g assert_match 'Test', 'TEST'  

I've tried fudging with assert_match to make an case insensitive compare but I have had no luck thus far and I cannot get past the old implicit conversion of Regexp into String.

module Test::Unit::Assertions    def assert_match matcher, obj, msg = nil      msg = message(msg) { "Expected #{mu_pp matcher} to match #{mu_pp obj}" }      assert_respond_to matcher, :"=~"      matcher = Regexp.new Regexp.escape matcher if String === matcher      assert matcher =~ /#{obj}/i, /#{msg}/i    end  end  

How to convert date and time into datetime/timestamp

Posted: 25 Jul 2016 06:29 AM PDT

I need to import some CSV data and they have a date field and a time field of the format below

{"date"=>"23/04/16", "day"=>"SATURDAY", "time"=>"17:06"}  

and i want to make that a timestamp and be the created_at field in the record.

What is the way to go about it?

Rails group by parent id

Posted: 25 Jul 2016 06:28 AM PDT

I have category and subcategory tables

category - parent

  has_many :subcategories  

subcategory - child with category_id key

  belongs_to :category  

i want to sort by parent id like

subcategory=1 parentId=1    subcategory=2 parentId=1       subcategory=122 parentId=1     subcategory=232 parentId=1          subcategory=12 parentId=2      subcategory=18 parentId=2  

and so on

i have tried

Subcategory.joins(:category).order('categories.id') and       Subcategory.joins(:category).group(['subcategories.title','categories.id']).order('categories.id')  

but it doesn't work

How i can sort it?

I don't care about subcategory order just need to set order by parentId

How to test pundit with devise

Posted: 25 Jul 2016 06:35 AM PDT

I would like to test authorization of Event controller on method edit. Pundit works fine when I am using app, however my tests don't work as I would like.

EventsController

def edit    authorize @event  end  

EventPolicy

attr_reader :user, :event    def initialize(user, event)    @user = user    @event = event  end    def edit?    event_host?  end    private    def event_host?    user == event.user  end  

ApplicationController

rescue_from Pundit::NotAuthorizedError, with: :user_not_authorized    private    def user_not_authorized    flash[:alert] = "You are not authorized to perform this action."    redirect_to(request.referrer || root_path)  end  

Controller test

RSpec.describe EventsController, type: :controller do      let(:event_host) { User.create(name: "Hostname", surname: "Hostsurname", city: "Lodz", email: "a@a.a", password: "password") }      let(:other_user) { User.create(name: "username", surname: "usersurname", city: "Lodz", email: "b@b.a", password: "password") }      let(:event) { event_host.events.create        ({          name: "Dungeon Games",          description: "We are going to have so much fun playing games!",          city: "ert",          address: "erter",          start_t: DateTime.parse("09/08/2016 17:00"),          end_t: DateTime.parse("09/08/2016 18:00")        })      }      it "raises error" do        sign_in(other_user)        expect { get :edit, params: { id: event.to_param } }.to raise_error(Pundit::NotAuthorizedError)        sign_out(other_user)      end    end  

And my error message:

Failure/Error: expect { get :edit, params: { id: event.to_param } }.to raise_error(Pundit::NotAuthorizedError) expected Pundit::NotAuthorizedError but nothing was raised

EventPolicySpec

require 'rails_helper'    RSpec.describe EventPolicy do    subject { described_class }      let(:event_host) { User.new(name: "Hostname", surname: "Hostsurname", city: "Lodz", email: "a@a.a", password: "password") }    let(:other_user) { User.new(name: "username", surname: "usersurname", city: "Lodz", email: "b@b.a", password: "password") }    let(:event) { event_host.events.new      ({          name: "Dungeon Games",          description: "We are going to have so much fun playing games!",          city: "ert",          address: "erter",          start_t: DateTime.parse("09/08/2016 17:00"),          end_t: DateTime.parse("09/08/2016 18:00")      })    }      permissions :update?, :edit? do      it "grants access if user is a host of event" do        sign_in(event_host)        expect(subject).to permit(event_host, event)        sign_out(event_host)      end        it "denies access if user is not a host of event" do        sign_in(other_user)        expect(subject).not_to permit(other_user, event)        sign_out(other_user)      end    end  end  

And I get: NoMethodError: undefined method `sign_in'

when I erase sign_in I get Failure/Error: user == event.user

NoMethodError: undefined method `user'

Installing Fetcher for Ruby on Rails

Posted: 25 Jul 2016 06:01 AM PDT

I want to use the Ruby plugin Fetcher to fetch e-mails to my web app.

The installation directive says :

Install using:

script/plugin install git://github.com/look/fetcher.git

I don't understand how I should use this command. Can someone explain it to me?

I am on Windows.

ruby on rails or python and django to work with database [on hold]

Posted: 25 Jul 2016 05:05 AM PDT

I have to program a webapp which has to write code in a database. and I want a something like a table or something similar as the gui what would you prefer ruby on rails or python and django. and why you prefer it?

thanks for your help

Update child attributes rails

Posted: 25 Jul 2016 06:07 AM PDT

I have a customer model and book_room model

class Customer < ApplicationRecord    has_many :book_rooms    accepts_nested_attributes_for :book_rooms  end    class BookRoom < ApplicationRecord    belongs_to :customer  end   

in the book_room controller the create method is from its parent

class BookRoomsController < ApplicationController   def create      @customer = Customer.find(params[:customer_id])      @customer_room = @customer.book_rooms.create(book_rooms_params)     flash[:notice] = "Customer has been added to room"     redirect_to customer_path(@customer)   end    def destroy      @customer = Customer.find(params[:customer_id])      @customer_room = @customer.book_rooms.find(params[:id])     @customer_room.destroy     flash[:notice] = "Customer room has been deleted"     redirect_to customer_path(@customer)   end    def edit      @customer = Customer.find(params[:customer_id])    end     def update      @customer = Customer.find(params[:customer_id])      @customer.book_rooms.update(book_rooms_params)     flash[:notice] = "Customer has checked out"     redirect_to @customer   end    private   def book_rooms_params      params.require(:book_room).permit(:room, :first_name, :last_name, :phone_number, :checked_out)   end  

end

in the Customer show page

<%= form_for [@customer, @customer.book_rooms.build] do |f| %>  <% @room = Room.all %>  <%= f.label "Room: "%>  <%= f.select(:room, @room.collect { |a| [a.room_number, a.id] }) %>  <%= f.submit "Enter" %>  <div class="col-md-12"><%= render @customer.book_rooms.order("created_at DESC") %></div>  

This works perfectly and all child objects get created. now when I try to edit the child attributes it doesn't update at all

heres the edit form in the book_room edit page/action

<%= form_for @customer do |f| %>  <%= f.fields_for :book_rooms, @customer.book_rooms do |f| %>    <%= f.check_box :checked_out %>  <% end %>  <%= f.submit "Enter" %>  

is there something i am doing wrong? why doesn't it update?

Customers controller

class CustomersController < ApplicationController  before_action :set_customer, only: [:show, :edit, :update, :destroy]  # POST /customers.json  def create  @customer = Customer.new(customer_params)  respond_to do |format|    if @customer.save      format.html { redirect_to @customer, notice: 'Customer was successfully created.' }      format.json { render :show, status: :created, location: @customer }    else      format.html { render :new }      format.json { render json: @customer.errors, status: :unprocessable_entity }    end  end  end  def update  respond_to do |format|    if @customer.update(customer_params)      format.html { redirect_to @customer, notice: 'Customer was successfully updated.' }      format.json { render :show, status: :ok, location: @customer }    else      format.html { render :edit }      format.json { render json: @customer.errors, status: :unprocessable_entity }    end    end  end    private  # Use callbacks to share common setup or constraints between actions.  def set_customer    @customer = Customer.find(params[:id])  end    # Never trust parameters from the scary internet, only allow the white list through.  def customer_params    params.require(:customer).permit(:first_name, :last_name, :phone_number, :sex, :book_rooms_attributes => [:checked_out])  end  

Split parameters into component parts

Posted: 25 Jul 2016 05:24 AM PDT

I have the following parameters when I process a form with multiple records. I wish to be able to take each individual campaign and process it accordingly.

 Parameters: {"utf8"=>"✓", "authenticity_token"=>"F2Mciu313dYUBOh7Ju0gSXrKa/yz6D6qZlVBMKOch4k=", "campaign"=>{"2"=>{"start_date"=>"2016-07-18 15:43:00", "end_date"=>"2016-10-15 12:20:00", "merchant_revenue"=>"10", "status"=>"Rejected", "notes"=>"aaaaaaaaaaaaaaaaaaaaaaaaaaa"}, "1"=>{"start_date"=>"2016-07-15 12:20:00", "end_date"=>"", "merchant_revenue"=>"10", "status"=>"Rejected", "notes"=>"bbbbbbbbbbbbbbbbbbbbbbbbbb"}}, "Commit"=>"Process"}  

How do I split this data so each record has a campaign contained within. Thanks.

Crontab throws error

Posted: 25 Jul 2016 07:37 AM PDT

I've below command in crontab, when I run this command in terminal it works fine but when I run this in crontab am getting the following error

  * * * * * cd /home/path/application && RAILS_ENV=development ./bundle exec rake namespacefolder:rake_file  

Error:

bundler: command not found: rake  Install missing gem executables with `bundle install`  

someone please help.

Unable to start neo4j service on ubuntu?

Posted: 25 Jul 2016 06:40 AM PDT

I have neo4j 2.2.1 installed .

java -version gives java version "1.7.0_101"

When i start the neo4j server rake neo4j:start

I'm getting this error:

Starting Neo4j in development...    ERROR: Unable to find java. (Cannot execute /home/jdk/jdk1.7.0_45/bin/java)     * Please use Oracle(R) Java(TM) 7 or OpenJDK(TM) to run Neo4j Server.   * Please see http://docs.neo4j.org/ for Neo4j Server installation instructions  rake aborted!  Unable to run: db/neo4j/development/bin/neo4j start  

Any idea ???

Invalid HTTP format, parsing fails

Posted: 25 Jul 2016 04:32 AM PDT

I was trying to make sure code I have written in Rails only runs on the development environment. So I tried to starts the rails server with a production environment via command:

rails s -e production  

I started to see the error:

Invalid request: Invalid HTTP format, parsing fails.      /home/mark/.rvm/gems/ruby-2.1.5/gems/thin-1.6.1/lib/thin/request.rb:84:in `execute'      /home/mark/.rvm/gems/ruby-2.1.5/gems/thin-1.6.1/lib/thin/request.rb:84:in `parse'      /home/mark/.rvm/gems/ruby-2.1.5/gems/thin-1.6.1/lib/thin/connection.rb:41:in `receive_data'      /home/mark/.rvm/gems/ruby-2.1.5/gems/eventmachine-1.0.7/lib/eventmachine.rb:187:in `run_machine'      /home/mark/.rvm/gems/ruby-2.1.5/gems/eventmachine-1.0.7/lib/eventmachine.rb:187:in `run'      /home/mark/.rvm/gems/ruby-2.1.5/gems/thin-1.6.1/lib/thin/backends/base.rb:73:in `start'      /home/mark/.rvm/gems/ruby-2.1.5/gems/thin-1.6.1/lib/thin/server.rb:162:in `start'      /home/mark/.rvm/gems/ruby-2.1.5/gems/rack-1.5.5/lib/rack/handler/thin.rb:16:in `run'      /home/mark/.rvm/gems/ruby-2.1.5/gems/rack-1.5.5/lib/rack/server.rb:264:in `start'      /home/mark/.rvm/gems/ruby-2.1.5/gems/railties-4.1.7/lib/rails/commands/server.rb:69:in `start'      /home/mark/.rvm/gems/ruby-2.1.5/gems/railties-4.1.7/lib/rails/commands/commands_tasks.rb:81:in `block in server'      /home/mark/.rvm/gems/ruby-2.1.5/gems/railties-4.1.7/lib/rails/commands/commands_tasks.rb:76:in `tap'      /home/mark/.rvm/gems/ruby-2.1.5/gems/railties-4.1.7/lib/rails/commands/commands_tasks.rb:76:in `server'      /home/mark/.rvm/gems/ruby-2.1.5/gems/railties-4.1.7/lib/rails/commands/commands_tasks.rb:40:in `run_command!'      /home/mark/.rvm/gems/ruby-2.1.5/gems/railties-4.1.7/lib/rails/commands.rb:17:in `<top (required)>'      script/rails:6:in `require'      script/rails:6:in `<main>'  

So I killed the server and ran rails s. However, I continue to get this error no matter what I try. What can i do?

Rspec testing POROs included in models rails

Posted: 25 Jul 2016 05:08 AM PDT

In my Order model I include a PORO class "ShipmentHandler". This PORO is located like this: app/models/order/shipment_handler.rb

I invoke this in my Order model like so:

def assign_shipments    ShipmentHandler.new(self).assign_shipments  end  

My PORO looks like:

class Order      class ShipmentHandler           def initialize(order)              @set_some_variables          end            def some_methods          end      end  end  

I'm trying to create spec to test the methods in my ShipmentHandler class. I'm not sure how to do this as I keep getting errors like uninitialized constant ShipmentHandler

I've tried to add it to my order_spec.rb like so:

describe Order do       describe Order::ShipmentHandler do      end  end  

and:

describe Order do       describe ShipmentHandler do      end  end  

Neither work. I've also tried creating a spec in spec/models/order/shipment_handler_spec.rb This also failed.

No comments:

Post a Comment