Saturday, October 29, 2016

Rails 5 - nested form (simple_form) - error on save of parent | Fixed issues

Newest questions tagged ruby-on-rails - Stack Overflow

Rails 5 - nested form (simple_form) - error on save of parent | Fixed issues


Rails 5 - nested form (simple_form) - error on save of parent

Posted: 29 Oct 2016 07:56 AM PDT

In my app that I am building to learn RoR, I use this form and get a type error on my AnnotationsController:

no implicit conversion of Symbol into Integer

for this line in the controller

def update      @annotation = Annotation.find(params[:id])      @annotation.update(annotation_params)      render 'edit'  end  

This is the form.

<%= simple_form_for @annotation,  html: { class: 'form-horizontal', multipart: true },      wrapper: :horizontal_form,      wrapper_mappings: {          check_boxes: :horizontal_radio_and_checkboxes,          radio_buttons: :horizontal_radio_and_checkboxes,          file: :horizontal_file_input,          boolean: :horizontal_boolean      } do |f| %>        <div class="btn-toolbar btn-group", role="toolbar">        <%= f.button :submit, :class => "btn btn-xs btn-default" %> <%= link_to 'List' , annotations_path, :class => "btn btn-xs btn-default" %>      </div>        <h4>Annotation</h4>        <%= f.error_notification %>        <div>        <ul class="nav nav-tabs">          <li class="active"><a data-toggle="tab" href="#tab1">Overview</a></li>          <% unless @annotation.new_record? %>          <li><a data-toggle="tab" href="#tab2">Tags <span class="label label-success"><%= @annotation.tags.count %></span></a></li>          <li><a data-toggle="tab" href="#tab3">Comments <span class="label label-success"><%= @annotation.comments.count %></span></a></li>          <% end -%>         </ul>      </div>      <br>      <div class=tab-content>            <div id="tab1" class="tab-pane fade in active">              <%= f.input :file, as: :file, input_html: { accept: ('application/pdf') } if @annotation.file.blank? %>                <%= f.input :name, placeholder: 'Enter name' %>                <%= f.input :description, placeholder: 'Description', :input_html => { :rows => 1 } %>              <%= f.association :sender, label: 'Submitted by' , prompt: 'Select sender' %>              <%#= f.association :receiver, label: 'Specific to', prompt: 'Select recipient' %>              <%= f.association :documenttype, label: 'Doc. type', :collection => Documenttype.active.order(:name), prompt: 'Select document type' %>              <%= f.input :currency, :collection => ["EUR","USD","GBP"], prompt:'Select currency' %>              <%= f.input :dateformat, :collection => ["dd/mm/yy", "dd/mm/yyyy", "dd-mm-yy", "dd-mm-yyyy", "dd.mm.yyyy"], prompt:'Select date format', label: 'Date format' %>              <%= f.input :locale_language, label: 'Doc. language', :collection => ["NL","EN"], prompt:'Select language' %>              <%= f.input :locale_id, :collection => ["nl-NL","en-US"], prompt:'Select locale Id', :length => 2 %>              <%= f.input :active, as: :boolean %>            </div>            <% unless @annotation.new_record? %>                      <div id="tab2" class="tab-pane fade in" >              <div class="row">                <%= render 'tags/form', :tagable => @annotation %> <!-- add the tag -->            </div>                <% @annotation.tags.each do |tag| %> <!--list all tags -->                  <% unless tag.content.blank?%>                          <%= f.simple_fields_for "tags_attributes[]", tag do |t| %>                              <div class="panel panel-body panel-default">                              <%= tag.id %>                              <%= params.inspect %>                                  <%= t.input :_destroy, as: :boolean, label: 'delete' %>                                  <%= t.input :content, placeholder: 'Tagged content' %>                              <%= t.association :tagtype, prompt: 'Select tag type', :collection => Tagtype.active.order(:name).where(:documenttype => @annotation.documenttype_id) %>                                      <%= t.input :key %>                                      <%= t.input :key_position, placeholder: 'add as: x1, y1, x2, y2' %>                                      <%= t.input :key_regex %>                                      <%= t.input :key_regex_options, :collection => ["i", "m", "x", "o"] %>                                      <%= t.input :value %>                                      <%= t.input :value_position, placeholder: 'add as: x1, y1, x2, y2' %>                                      <%= t.input :value_regex %>                                      <%= t.input :value_regex_options, :collection => ["i", "m", "x", "o"], :input_html => { :class => "check-boxes-inline" } %>                          </div>                          <% end -%>                      <% end -%>                  <% end -%>                <% end -%>          </div>      <% end -%>  

After having studies documentation, rails casts and wiki's (for created it following this post) for days I don't get it to work.

Any advice, corrections and suggestions welcome!

Why Rails create my text_fields with the same "name" value?

Posted: 29 Oct 2016 07:33 AM PDT

I have the next code:

text.gsub(/%{(\w*)}/, text_field_tag(/(?<=%{)[^%]*(?=})/.match(text), nil)).html_safe  

So if I have the next text input: %{abc}, it will replace by %{abc} with text_field and will call its name as abc. But if I have %{abc} -- %{cba} it will add 2 text_fields but with the same name values, abc and abc. But I need to make it as abc and for the second text_field cba.

What's wrong and how can I improve my code?

rails 5 carrierwave no route matches for image

Posted: 29 Oct 2016 07:09 AM PDT

I need some help. I am using rails 5 and carrierwave to upload images. the issue I am having is the images are saved but will not display, I get a no route matches GET..... I am storing the images in a uploads folder at Rails.root

image_uploader.rb

  def store_dir     "uploads/#{model.user_id}/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"    end  

carrier_wave.rb

require 'carrierwave/orm/activerecord'  require 'carrierwave'  CarrierWave.configure do |config|   config.root = Rails.root  end  

This is the error that I am getting in the logs:

Started GET "/uploads/2/uitem/image/26/A_penrose-small.jpg" for ::1 at 2016-10-29 16:06:27 +0200    ActionController::RoutingError (No route matches [GET] "/uploads/2/uitem/image/26/A_penrose-small.jpg"):  

Any Help would be greatly appreciated, I have been searching all over and cannot find a solution. Thank you

How to decrease query execution time on a db with 20 million records | Rails, Postgres

Posted: 29 Oct 2016 08:03 AM PDT

I have a Rails app with Postgres db. It has 20 million records. Most of the queries use ILIKE. I have created a triagram index on one of the columns.

Before adding the triagram index, the query execution time was ~200s to ~300s (seconds not ms)

After creating the triagram index, the query execution time came down to ~30s.

How can I reduce the execution time to milliseconds?

Also are there any good practices/suggestions when dealing with a database this huge?

Thanks in advance :)

Ref : Faster PostgreSQL Searches with Trigrams

Edit: 'Explain Analyze' on one of the queries

EXPLAIN ANALYZE SELECT COUNT(*) FROM "listings" WHERE (categories ilike '%store%');                            QUERY PLAN          --------------------------------------------------------------------------   Aggregate  (cost=716850.70..716850.71 rows=1 width=0) (actual time=199354.861..199354.861 rows=1 loops=1)   ->  Bitmap Heap Scan on listings  (cost=3795.12..715827.76 rows=409177 width=0) (actual time=378.374..199005.008 rows=691941 loops=1)       Recheck Cond: ((categories)::text ~~* '%store%'::text)       Rows Removed by Index Recheck: 7302878       Heap Blocks: exact=33686 lossy=448936       ->  Bitmap Index Scan on listings_on_categories_idx  (cost=0.00..3692.82 rows=409177 width=0) (actual time=367.931..367.931 rows=692449 loops=1)           Index Cond: ((categories)::text ~~* '%store%'::text)   Planning time: 1.345 ms   Execution time: 199355.260 ms   (9 rows)  

NameError in ProjectsController#index

Posted: 29 Oct 2016 06:47 AM PDT

In my rails app I am getting the following error:

NameError in ProjectsController#index  app/controllers/projects_controller.rb:6:in `index'  

My routes look like this:

RailsStarter::Application.routes.draw do  resources :projects    root :to => 'pages#home'  match '/' => 'pages#home'  match '/overview' => 'pages#overview'  match '/recruitmentInfo' => 'pages#recruitmentInfo'  

And the problem controller:

 class ProjectsController < ApplicationController     # GET /projects   # GET /projects.json   def index   @projects = ::Project.all     respond_to do |format|     format.html # index.html.erb     format.json { render json: @projects }   end  end  

My investigations so far showed that Project is not yet initialized, but this shouldn't matter as it is a constructor, in its own class. I even tryed precompiling that by adding this line config.autoload_paths += %W( #{config.root}/app/controllers) to application.rb. Nothing seems yet to work. Any ideas will be greatly appreciated. Thanks!

Unable to run gem pristine on rails app

Posted: 29 Oct 2016 06:16 AM PDT

So I'm trying to run my first rails app on my new Mac and am having some difficulties. When trying to generate a basic model, I get this error:

Ignoring bcrypt-3.1.11 because its extensions are not built. Try: gem pristine bcrypt --version 3.1.11

bcrypt is commented out in the gemfile so I don't know why I'm getting this error, and when I run gem pristine bcrypt --version 3.1.11, it seems to work, but doesn't change the bcrypt error.

I can't seem to figure out what I'm doing wrong. I never had this issue on my pc. I appreciate any help.

Jquery validation plugin doesn't work with fields that have bracket name

Posted: 29 Oct 2016 06:12 AM PDT

This question's got asked a lot on Stackoverflow but I can't seem to resolve the problem using the solution of turning

$bookingForm.validate({  errorElement: "div",  rules: {    booking[name]: {      required: true,      minlength: 2    },    booking[email]: {      required: true,      email: true    } ...   

into

$bookingForm.validate({  errorElement: "div",  rules: {    "booking[name]": {      required: true,      minlength: 2    },    "booking[email]": {      required: true,      email: true    }  },  

Note the bracketed names are put in quotes. Jquery and Jquery validation plugin both load fine. No errors shown in console. I'm using rails5.0.0.1. Previously I used middleman and the validation plugin worked pretty well (with un-bracketed names). Has anyone had this issue with jquery validation plugin in rails?

Rails 5 CarrierWave Polymorphic Image upload in Nested Form throws NoMethod Error "undefined method `image_changed?'"

Posted: 29 Oct 2016 06:10 AM PDT

I have a polymorphic image I am trying to get to upload via CarrierWave, but I can't seem to get all the details right. Currently, I am getting the NoMethod error in the title, "undefined method `image_changed?'" I see there are many related questions already posted, but the solutions provided haven't been applicable to my case, at least that I've been able to find. Any help is appreciated. Here is the relevant code. Please let me know if I can provide anything else.

Uploader:

# app/uploaders/image_uploader.rb  `class ImageUploader < CarrierWave::Uploader::Base    storage :file      def store_dir      "uploads/#{model.class.to_s.underscore}/#{mounted_as}/#{model.id}"    end      version :thumb do      process resize_to_fill: [280, 280]    end      version :small_thumb, :from_version => :thumb do      process resize_to_fill: [20, 20]    end      def extension_white_list      %w(jpg jpeg gif png)    end  end  

Image Model:

#app/models/image.rb  class Image < ApplicationRecord    mount_uploader :image, ImageUploader    belongs_to :imageable, polymorphic: true  end  

Post Model:

#app/models/post.rb  class Post < ApplicationRecord    mount_uploader :image, ImageUploader    has_one :image, as: :imageable, dependent: :destroy      validates :title, presence: true, length: { maximum: 150, minumum: 3 }    validates :content, presence: true, length: { minimum: 5 }      scope :featured, -> { where(is_featured: true) }    scope :authored_by, -> (user) { where(:user => user) }  end  

Post Controller:

#app/controllers/admin/posts_controller  class Admin::PostsController < ApplicationController    before_action :set_post, only: [:show, :edit, :update, :destroy]    def update      unless params[:post][:image].empty?        @post.build_image(params[:post][:image][:original_filename]).save      end        respond_to do |format|        if @post.update_attributes(post_params)          format.html { redirect_to permalink_path(:blog => @blog.name.parameterize, :date => @post.link_date, :title => @post.title.parameterize) }          format.json { render :show, status: :ok, location: @post }        else          format.html { render :edit }          format.json { render json: @post.errors, status: :unprocessable_entity }        end      end    end      private      def set_post        @post = Post.find(params[:id])      end        def post_params        params.require(:post).permit(:title, :content, :user_id, :weblog_id, :is_featured, :category_ids => [], :tag_ids => [],          image_attributes: [:image])      end  end  

Edit Form:

#app/views/admin/posts/_form.html.erb  <div class="container">  <%= form_for [:admin,post], :html => {:multipart => true} do |f| %>    <div class="row">      <div class="form-group">        <%= f.label :title %><br/>        <%= f.text_field :title, class: "form-control" %>      </div>        <div class="form-group">        <%= f.label :content %><br/>        <%= f.text_area :content, class: "form-control ckeditor" %>      </div>        <div class="form-group">        <%= f.check_box :is_featured %>        <%= f.label :is_featured %>?      </div>        <h4>Image</h4>      <%= f.fields_for Image.new do |i| %>        <div class="row">          <div class="col-md-4">            <%= image_tag(post.image_url, class: "img-responsive")  if post.image? %>          </div>          <div class="col-md-8">            <div class="form-group">              <%= i.label :image, "Choose Image" %><br/>              <%= i.file_field :image %>              <%= f.hidden_field :image_cache %>            </div>          </div>        </div>      <% end %>        <div class="form-group margin-top30">        <%= f.submit class: "btn btn-primary" %>      </div>    </div>  <% end %>  

Devise destroying user - uninitialized constant User::Profile

Posted: 29 Oct 2016 06:13 AM PDT

Hey I'm trying to destroy a user, who was created with devise.

Here are my files:

users_controller.rb

before_action :find_user  def destroy      @user.destroy      if @user.destroy          redirect_to admin_users_path, notice: "User destroyed"      end  end  

routes.rb

devise_for :users  match 'users/:id' => 'users#destroy', :via => :delete, :as => :admin_destroy_user  

view:

= link_to "delete", admin_destroy_user_path(u), method: :delete, data: {confirm: "You sure?"}  

But I get following error message:

NameError in UsersController#destroy  uninitialized constant User::Profile  

wrong number of arguments (given 4, expected 2)

Posted: 29 Oct 2016 05:59 AM PDT

This is my controller.

class DogsController < ApplicationController      def create   @dog=current_admin.dogs.build(dog_params)   if @dog.save    redirect_to current_admin   else    render 'dogs/new'   end  end    private     def dog_params   params.require(:dog).permit(:name, :content , :age , :personality , :breed ,:picture, :admin_id)   end  end  

And this is my view.

    <%=form_for(@dog, html: {multipart: true}) do |f| %>        <%= render 'shared/dog_error_messages' , f: @dog %>         <div class="field">            <%= f.label :name , class:"form-label"  %><br />           <%= f.text_field :name, autofocus: true  %>      </div>      <div class="field">           <%= f.label :content , class:"form-label"  %><br />           <%= f.text_area :content , cols: 70 , rows: 20 ,  placeholder: '犬ちゃんの特徴' %>      </div>      <div class="field">           <%= f.label :age , class:"form-label"  %><br />           <%= f.number_field :age , min: 0 , max: 15 , step: 1 %>      </div>      <div class="field">           <%= f.label :personality , class:"form-label"  %><br />           <%= f.select :personality , %w[オス メス] , { include_blank: '選択して下さい'} , class: 'pb' %>      </div>      <div class="field">          <%= f.label :breed , class:"form-label"  %><br />          <%= f.select :breed , %w[ゴールデンレトリーバー トイプードル] , { include_blank: '選択して下さい'}  %>      </div>      <div class="field">         <%= f.label :picture , class:"form-label"  %><br />         <%= f.file_field :picture , class:'dog-form-picture' , accept: 'image/jpeg,image/gif,image/png' %>      </div>       <div class="actions">         <%= f.submit '追加する' , class:' btn btn-primary btn-lg'  %>      </div>        <% end %>       </div>    </div>   </div>  

And This is my model.

    class Dog < ActiveRecord::Base          belongs_to :admin           has_many :likes , dependent: :destroy          default_scope -> {order(created_at: :desc)}          mount_uploader :picture , PictureUploader            validates :name , presence: true          validates :content , presence: true , length: {maximum:300}          validates :age , presence: true          validates :personality , presence: true          validates :breed , presence: true          validates :admin_id , presence: true          validates :picture , presence: true        end  

I'm also pretty new to Ruby on Rails. The error I'm getting is:ArgumentError in DogsController#create wrong number of arguments (given 4, expected 2) Please tell me why I have an error in {def create @dog=current_admin.dogs.build(dog_params)}. My code doesn't pass any parameters.

Expected exactly 2 elements matching "a [href="/"]", found 0

Posted: 29 Oct 2016 05:57 AM PDT

I'm trying to check how many links are routed to root_path. My question is why the route in my _header.html.erb file are not counted by assert_select?

(I'm a beginner to code and rails and I'm following Michael Hartl's tutorial)

root_path is used in the page twice:

 <%= link_to "sample app", root_path, id: "logo" %>   <li><%= link_to "Home",    root_path %></li>  

Here is my code for the integration test:

require 'test_helper'  class SiteLayoutTest < ActionDispatch::IntegrationTest    test "layout links" do      get root_path      assert_template 'static_pages/home'      assert_select "a [href=?]", root_path, count: 2      assert_select "a [href=?]", help_path      assert_select "a [href=?]", about_path      assert_select "a [href=?]", contact_path    end  end  

This is the partial code for my HTML file (_header.html.erb):

<header class="navbar navbar-fixed-top navbar-inverse">    <div class="container">      <%= link_to "sample app", root_path, id: "logo" %>      <nav>        <ul class="nav navbar-nav navbar-right">          <li><%= link_to "Home",    root_path %></li>          <li><%= link_to "Help",    help_path %></li>          <li><%= link_to "Log in", '#' %></li>        </ul>      </nav>    </div>  </header>  

When I run $bundle exec rake test:integration, it gives me 1 failure which is:

FAIL["test_layout_links", SiteLayoutTest, 2016-10-20 16:03:19 +0000]   test_layout_links#SiteLayoutTest (1476979399.42s)          Expected exactly 2 elements matching "a [href="/"]", found 0..          Expected: 2            Actual: 0          test/integration/site_layout_test.rb:8:in `block in <class:SiteLayoutTest>'  

Issue in creating an instance in rpsec

Posted: 29 Oct 2016 05:39 AM PDT

In book.rb we have this code

tracked only: [:create], owner: Proc.new{ |controller, model| controller.current_user }  

so when I create an instance of book model in the controller rspec it is generating an error

NoMethodError:   undefined method `current_user' for nil:NilClass  

How can I solve this issue . Please help. Thanks in advance

Mangopay - dont work redirect for enter pasword 3d secure

Posted: 29 Oct 2016 05:34 AM PDT

If card dont accept 3d secure, payment complete without error, but with mode 3d secure is no redirect to the page entered secret password.

Logic in following files:

class PaymentsController < ApplicationController    before_action :check_payment_authorize, only: [:new]      def new      @contract = Contract.find(session[:contract_id])        # Register card for user      @card_preregistration = MangoPay::CardRegistration.create(UserId: current_user.mangopay_id,                                                                Currency: 'EUR',                                                                CardType: 'CB_VISA_MASTERCARD')        session[:card_id] = @card_preregistration['Id']        locals card_reg: @card_preregistration    end      def create    end      def finialize_payment      binding.pry      @contract = Contract.find(session[:contract_id])        begin        card_registration = MangoPay::CardRegistration.update(session[:card_id], RegistrationData: "data=#{params['data']}",                                                                                 Tag: 'custom tag')          if card_registration['Status'] != 'VALIDATED'          flash[:error] = 'Cannot create card. Payment has not been created.'        end        # get created virtual card object        card = MangoPay::Card.fetch(card_registration['CardId'])          # create pay-in CARD DIRECT        payIn = MangoPay::PayIn::Card::Direct.create(CreditedWalletId: current_user.wallet_id,                                                     CardId: card['Id'],                                                     AuthorId: card_registration['UserId'],                                                     Tag: 'deposit',                                                     SecureModeReturnURL: contract_url(@contract),                                                     DebitedFunds: { Amount: (@contract.amount*100).to_i, Currency: 'EUR' },                                                     Fees: { Amount: 0, Currency: 'EUR' },                                                     # payment type as CARD                                                     PaymentDetails: { CardType: card['CardType'], CardId: card['Id'] },                                                     SecureMode: "FORCE")       binding.pry            # if created Pay-in object has status SUCCEEDED it's mean that all is fine        if payIn['Status'] == 'SUCCEEDED'          respond_to do |format|            @contract.update_attributes(payment_id: payIn['Id'], paid: true)            format.json { render json: { url: contract_url(@contract) } }            @contract.state_machine.transition_to(:proposed)            @contract.project.state_machine.transition_to(:has_proposed_contract)            @contract.proposal.state_machine.transition_to(:has_proposition)            ContractMailer.contract_proposed_client(@contract).deliver_later            ContractMailer.contract_proposed_contractor(@contract).deliver_later          end        end        #else          # if created Pay-in object has status different than SUCCEEDED          # that occurred error and display error message          # flash[:notice] = payIn['ResultMessage']         # flash[:notice] = 'Invalid card number'          # redirect_to :back          # format.json { head 500 }        

No comments:

Post a Comment