mercredi 28 février 2018

onclick on link_to user_path i get UsersController#show is missing a template ruby on rails

I'm getting error "UsersController#show is missing a template" once i click on span in your_list.html.erb I know the error it has to be cause i misplaced my show.html.erb file

borroup/app/views/reservations/your_list.html.erb

          <span class="pull-right text-center">
            <%= image_tag avatar_url(list.item.user), class: "img-circle avatar-medium" %></br>
            <%= link_to user_path(list.item.user) do %>
                <%= list.item.user.fullname %>
            <% end %>
          </span>

This is my user controller borroup/app/controllers/users_controller.rb

 class UsersController < ApplicationController
      def show
      @user = User.find(params[:id])
     end
  end

I do have show.html.erb in this path borroup/app/views/users/show.html.rb

and lastly in my routes.rb

Rails.application.routes.draw do
 root 'pages#home'
  devise_for :users,
          path: '',
          path_names:{sign_in: 'login', sign_out: 'logout', edit: 
          'profile', sign_up: 'registration'},
          controllers: {omniauth_callbacks: 'omniauth_callbacks' , 
          registrations: 'registrations'}
          # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
resources :users, only: [:show]
resources :items, except: [:edit] do
member do
  get 'listing'
  get 'pricing'
  get 'description'
  get 'photo_upload'
  get 'location'
  get 'preload'
  get 'preview'
end
   resources :photos, only: [:create, :destroy]
   resources :reservations, only: [:create]
   end
   get '/your_list' => 'reservations#your_list'
 end

Response for preflight is invalid (redirect) - Rails 5, Omniauth, Facebook login

I am following this example for Facebook login with Omniauth and Rails 5: Link to Omniauth. The problem is that, when I click on the link for login, right before redirects to Facebook, I am getting this error in the console (2 times):

Failed to load https: // http://ift.tt/2CPCWv7 Response for preflight is invalid (redirect)

This is my view:

<%= link_to 'FB LOGIN', user_facebook_omniauth_authorize_path %>

which is this HTML:

<a href="/auth/facebook">FB LOGIN</a>

and point to this omniauth_callbacks_controller:

class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController

  def create
    byebug
    @user = User.from_omniauth(request.env["omniauth.auth"])
....

I have byebug in this method, but this does not matter. With or without it, I am getting same error in the browser, before redirecting.

I think the error is because it redirects to Facebook first, but I don't know how to fix it.

Create data with multiple nested attributes in rails

I am trying to create an item with nested attributes, these are my tables

1) Item

    has_many :items_modifier_groups, dependent: :destroy
    has_many :items_modifier_group_items, dependent: :destroy

    attr_accessible :items_modifier_groups_attributes, :items_modifier_group_items_attributes
    accepts_nested_attributes_for :items_modifier_groups, :items_modifier_group_items

2) ModifierGroup
    attr_accessible: tag_id

3) ItemsModifierGroup

    belongs_to :modifier_group
    belongs_to :item
    has_many :items_modifier_group_items, dependent: :destroy

    attr_accessible :item_id, :modifier_group_id, :modifier_group_attributes, :items_modifier_group_items_attributes
    accepts_nested_attributes_for :modifier_group, :items_modifier_group_items

4) ItemsModifierGroupItem - Table4

    belongs_to :items_modifier_group
    belongs_to :item

    attr_accessible :items_modifier_group_id, :item_id, :pre_select

Parameter to create from console

c = Item.new("name" => "test1", "items_modifier_groups_attributes"=>{"0"=>{"items_modifier_group_items_attributes"=>{"0"=>{"pre_select"=>"true"}},"min_item"=>"1", "modifier_group_attributes"=>{ "tag_id"=>"5" }}})

c.save

So when it create one item the item_id is nil in ItemsModifierGroupItem table but item_id is created in ItemsModifierGroup table, am i missing anything in the params?

mardi 27 février 2018

Ruby on Rails view iterrates through object even when object is nil

I am a beginner when it comes to ROR and programming in general. I was working through the basic getting started guide in the documentation and am working on creating a comments view for a blog. I have the following code in my view to render all comments on an article -

<% @article.comments.each do |comment| %>
  <p>
    <strong>Commenter: </strong>
    <%= comment.commenter %>
  </p>
  <p>
    <strong>Comment: </strong>
    <%= comment.body %>
  </p>
<% end %>

I am having trouble understanding why this code renders the 'Commenter:' and 'Comment:' titles even when there is no comment associated with the specific article?!

I also tried wrapping the above code in -

<% if @article.comments.all.empty? == false %>
  <!--Code Above-->
<% end %>

just to experiment with it.This will prevent the titles from being rendered if there is no comments however when I add one comment, the title get rendered again in addition to the comment just added. I just need an explanation of this to better understand what is going on.

Chunk upload media to twitter uisng ruby 1.9.3

I am uploading large video to Twitter and getting erros

media = File.open('/home/geobeats/Downloads/test.mp4', 'rb')
segment_id = 0
bytes_sent = 0
access_token = Oauth::Twitter.new.access_token
resp_1 = access_token.post("https://upload.twitter.com/1.1/media/upload.json", 
  {command: 'INIT', media_type: 'video/mp4', total_bytes: media.size, media_category: 'tweet_video'})

while bytes_sent < media.size
  chunk = media.read(4*1024*1024).encode('utf-8', 'binary', invalid: :replace, undef: :replace, replace: '')
  req = access_token.post("https://upload.twitter.com/1.1/media/upload.json", 
    {command: 'APPEND', media_id: JSON.parse(resp_1.body)['media_id'], segment_index: segment_id, media: chunk})

  p req.body

  segment_id = segment_id + 1
  bytes_sent = media.tell
end

Every time it gives error at APPEND call

lundi 26 février 2018

Why an AccessDenied error on S3 files?

Some of the files uploaded on S3 can't be read because of an AccessDenied error. It was working well so far...

Gemfile

ruby '2.2.0'
gem 'rails', '3.2.22.2'
gem 'pg', '0.18.4'
gem 'sprockets', '2.2.3'
gem 'carrierwave', '0.11.0'
gem 'fog', '1.38.0', require: 'fog/aws'

carrierwave.rb

if Rails.env.test?
  CarrierWave.configure do |config|
    config.storage = :file
    config.enable_processing = false
  end
else
  CarrierWave.configure do |config|
    config.storage = :fog
    config.fog_credentials = {
      provider: Figaro.env.fog_provider,
      aws_access_key_id: Figaro.env.fog_aws_access_key_id,
      aws_secret_access_key: Figaro.env.fog_aws_secret_access_key,
      region: Figaro.env.fog_region,
    }

    config.fog_directory  = "mycompany-#{Rails.env}"
    config.fog_public     = true
    config.fog_attributes = { 'Cache-Control' => "max-age=#{365.days.to_i}" }
    config.permissions = 0666
  end
end

URL I'm trying to reach:

https://mycompany-production.s3.amazonaws.com/uploads/coaching/attachment/1735/File-Uploaded-0001.pdf

The error AWS give me:

<Error>
    <Code>AccessDenied</Code>
    <Message>Access Denied</Message>
    <RequestId>12D13432D83CD9DE</RequestId>
    <HostId>
        SKLsZ20cJ4x2uxxIR/6ejZ6w6rpbH9HU18+22Sm6/sr+t1mVwe8+zWpe+lFl0v05GMU0TWtcNOI=
    </HostId>
</Error>

How can I set the Read-Only attribute on some folders? AWS S3 allow me to "Make the folder public" but I don't want that.

Thank you

dimanche 25 février 2018

Active Admin Show Page for one model is not working

I am integrating Active Admin into a Ruby on Rails app. I registered all my models and already set up index, filter and show for all the models. Everything is working, but for one model the admin/show page is not running.

When calling the show page from the admin/index page, I get:

NoMethodError in Admin/safts#show

Showing /Users/xxxxxx/.rvm/gems/ruby-1.8.7-p374@xxxxxx/gems/activeadmin-0.6.0/app/views/active_admin/resource/show.html.arb where line #1 raised:

undefined method `empty?' for #<Keyword:0x105498800>
Extracted source (around line #1):

1: insert_tag renderer_for(:show)

Request

Parameters:

{"id"=>"9"}

The relative entry in my log file is:

Started GET "/admin/safts/9" for 127.0.0.1 at Sun Feb 25 14:48:04 +0100 2018
Processing by Admin::SaftsController#show as HTML
  Parameters: {"id"=>"9"}
  [1m[35mAdminUser Load (0.6ms)[0m  SELECT `admin_users`.* FROM `admin_users` WHERE `admin_users`.`id` = 2 LIMIT 1
  [1m[36mSaft Load (0.2ms)[0m  [1mSELECT `safts`.* FROM `safts` WHERE `safts`.`id` = ? LIMIT 1[0m  [["id", "9"]]
  [1m[35mKeyword Load (0.3ms)[0m  SELECT `keywords`.* FROM `keywords` WHERE `keywords`.`id` = 138 LIMIT 1
  Rendered /Users/xxxxxx/.rvm/gems/ruby-1.8.7-p374@xxxxxx/gems/activeadmin-0.6.0/app/views/active_admin/resource/show.html.arb (3.1ms)
Completed 500 Internal Server Error in 10ms

ActionView::Template::Error (undefined method `empty?' for #<Keyword:0x1052a0890>):
1: insert_tag renderer_for(:show)
  activemodel (3.2.5) lib/active_model/attribute_methods.rb:407:in `method_missing'
  activerecord (3.2.5) lib/active_record/attribute_methods.rb:149:in `method_missing'
  activeadmin (0.6.0) lib/active_admin/views/pages/show.rb:38:in `default_title'
  activeadmin (0.6.0) lib/active_admin/views/pages/show.rb:14:in `title'
  activeadmin (0.6.0) lib/active_admin/views/pages/base.rb:25:in `build_active_admin_head'
  arbre (1.0.1) lib/arbre/context.rb:92:in `with_current_arbre_element'
  arbre (1.0.1) lib/arbre/element/builder_methods.rb:49:in `within'
  activeadmin (0.6.0) lib/active_admin/views/pages/base.rb:24:in `build_active_admin_head'
  activeadmin (0.6.0) lib/active_admin/views/pages/base.rb:9:in `build'
  arbre (1.0.1) lib/arbre/element/builder_methods.rb:30:in `build_tag'
  arbre (1.0.1) lib/arbre/context.rb:92:in `with_current_arbre_element'
  arbre (1.0.1) lib/arbre/element/builder_methods.rb:26:in `build_tag'
  arbre (1.0.1) lib/arbre/element/builder_methods.rb:39:in `insert_tag'
  activeadmin (0.6.0) app/views/active_admin/resource/show.html.arb:1:in `___sers__tephan__rvm_gems_ruby_______p____saftzine_gems_activeadmin_______app_views_active_admin_resource_show_html_arb___1026777847_2195984600'
  arbre (1.0.1) lib/arbre/context.rb:45:in `instance_eval'
  arbre (1.0.1) lib/arbre/context.rb:45:in `initialize'
  activeadmin (0.6.0) app/views/active_admin/resource/show.html.arb:1:in `new'
  activeadmin (0.6.0) app/views/active_admin/resource/show.html.arb:1:in `___sers__tephan__rvm_gems_ruby_______p____saftzine_gems_activeadmin_______app_views_active_admin_resource_show_html_arb___1026777847_2195984600'
  actionpack (3.2.5) lib/action_view/template.rb:145:in `send'
  actionpack (3.2.5) lib/action_view/template.rb:145:in `render'
  activesupport (3.2.5) lib/active_support/notifications.rb:125:in `instrument'
.
.
.
  script/rails:6:in `gem_original_require'
  script/rails:6:in `require'
  script/rails:6


  Rendered /Users/xxxxxx/.rvm/gems/ruby-1.8.7-p374@xxxxxx/gems/actionpack-3.2.5/lib/action_dispatch/middleware/templates/rescues/_trace.erb (0.7ms)
  Rendered /Users/xxxxxx/.rvm/gems/ruby-1.8.7-p374@xxxxxx/gems/actionpack-3.2.5/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (0.6ms)
  Rendered /Users/xxxxxx/.rvm/gems/ruby-1.8.7-p374@xxxxxx/gems/actionpack-3.2.5/lib/action_dispatch/middleware/templates/rescues/template_error.erb within rescues/layout (9.8ms)

The rails model is:

class Saft < ActiveRecord::Base
    attr_accessible :colour, :cover_alt, :description, :number, :short, :title_id

# Associations
    has_and_belongs_to_many :keywords, :join_table => "safts_keywords" 
    has_many :authors, :through => :texts 
    has_many :texts 
    belongs_to :title, :class_name => "Keyword", :foreign_key => "title_id"
    has_one :cover
    has_many :stamps
    has_many :images
end

The ActiveAdmin resource is:

ActiveAdmin.register Saft do
    index do
        column "Issue", :number 
        column "Title", :title_id do |saft|
            link_to saft.title.word.capitalize, saft_path(saft)
        end
        column :short
        column :description
        column :colour
        column :cover_alt
        default_actions
    end

    # Filter only by:
    filter :title_id, :label => 'Title', :as => :select, :collection => Saft.all.map{|u| ["#{u.title.word.capitalize}", u.id]}
    filter :short

    form do |f|
        f.inputs "Saft Details" do
            f.input :number, :label => "Number of issue"
            f.input :title_id, :label => 'Title', :as => :select, :collection => Keyword.all.map{|u| ["#{u.word.capitalize}", u.id]}
            f.input :short
            f.input :description
            f.input :colour, :label => "Colour (in hex)"
            f.input :cover_alt
        end
        f.actions
    end

    show do
        panel "Saft Details" do
            attributes_table_for saft do
                row :id
                row :number
                row :title_id
                row :short
                row :description
                row :colour
                row :cover_alt
                row :created_at
                row :updated_at
            end
        end
        active_admin_comments
    end
end

Just for context: SAFT is a magazine, with texts, images, authors, etc. All the other resources are working well in Admin. Only the show page of SAFT is not working. What could it be?

samedi 24 février 2018

Uploading large files with Rails 5 and Carrierwave

I have a HTML form for uploading video files in Rails 5. I am using Carrierwave with the standard generated uploader. Uploader with validation for file extension. When I try to upload large video files (2GB and more), I am getting this error:

Puma caught this error: failed to allocate memory (NoMemoryError)

This is full trace of the error:

Puma caught this error: failed to allocate memory (NoMemoryError) C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/rack-2.0.3/lib/rack/multipart/parser.rb:186:in on_read' C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/rack-2.0.3/lib/rack/multipart/parser.rb:72:inblock in parse' C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/rack-2.0.3/lib/rack/multipart/parser.rb:70:in loop' C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/rack-2.0.3/lib/rack/multipart/parser.rb:70:inparse' C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/rack-2.0.3/lib/rack/multipart.rb:52:in extract_multipart' C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/rack-2.0.3/lib/rack/request.rb:472:inparse_multipart' C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/rack-2.0.3/lib/rack/request.rb:335:in POST' C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/rack-2.0.3/lib/rack/method_override.rb:39:inmethod_override_param' C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/rack-2.0.3/lib/rack/method_override.rb:27:in method_override' C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/rack-2.0.3/lib/rack/method_override.rb:15:incall' C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/rack-2.0.3/lib/rack/runtime.rb:22:in call' C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/activesupport-5.1.4/lib/active_support/cache/strategy/local_cache_middleware.rb:27:incall' C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/actionpack-5.1.4/lib/action_dispatch/middleware/executor.rb:12:in call' C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/rack-livereload-0.3.16/lib/rack/livereload.rb:23:in_call' C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/rack-livereload-0.3.16/lib/rack/livereload.rb:14:in call' C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/actionpack-5.1.4/lib/action_dispatch/middleware/static.rb:125:incall' C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/rack-2.0.3/lib/rack/sendfile.rb:111:in call' C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/engine.rb:522:incall' C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/puma-3.10.0/lib/puma/configuration.rb:225:in call' C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/puma-3.10.0/lib/puma/server.rb:605:inhandle_request' C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/puma-3.10.0/lib/puma/server.rb:437:in process_client' C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/puma-3.10.0/lib/puma/server.rb:301:inblock in run' C:/RailsInstaller/Ruby2.3.3/lib/ruby/gems/2.3.0/gems/puma-3.10.0/lib/puma/thread_pool.rb:120:in `block in spawn_thread'

I am using Windows 10. For production I will switch to Linux, but now I am developing in Windows. May be with Linux I will get same error, I don't know. How to upload large files with Carrierwave (even more than 5GB) ?

vendredi 23 février 2018

Returning an ActiveRecord Object from two different Tables

I am trying to return an ActiveRecord object consisting of two different objects from two different tables. They have the following relations:

class User < ApplicationRecord
  has_many :posts, dependent: :destroy
  has_many :pictures, dependent: :destroy

  # Ideally user.timeline returns all of a user's posts and pictures as an active record relation.

  def timeline
      Post.where("(user_id = :user_id)", user_id: id)
      Picture.where("(user_id = :user_id)", user_id: id)    
  end
end

class Post < ApplicationRecord
  belongs_to :user
end

class Picture < ApplicationRecord
  belongs_to :user
end

I would like to be able to call user.timeline and have all of a user's posts and pictures returned together as one active record relation.

I have tried: Post.where("(user_id = :user_id)", user_id: id) + Picture.where("(user_id = :user_id)", user_id: id). This returns all the objects I want, but as an array, not an active record relation.

Is there any way this can be done?

'+' symbol is getting replaced with space in a string when I read the url parameter in rails

Iam hitting a method in rails through ajax. The get url can be seen below,

/learners/-638284588?is_combined_page=true&email=test0221k+staging@tt.com&type=ld"

In log I can see the below entries,

  Started GET "/learners/-638284588?is_combined_page=true&    email=test0221k+staging@rosettastone.com&type=lcd" for 127.0.0.1 at Fri Feb 23 09:31:56 -0500 2018
  Processing by Extranet::LearnersController#show as HTML
  Parameters: {"type"=>"ld", "email"=>"test0221k staging@tt.com", "is_combined_page"=>"true", "id"=>"-638284588"}
  [WARNING] Audit logging has been enabled for Account
  parameter ----------------> {"type"=>"lcd", "email"=>"test0221k staging@tt.com", "controller"=>"extranet/learners", "is_combined_page"=>"true", "action"=>"show", "id"=>"-638284588"} test0221k staging@tt.com

In the GET request url email parameter can be seen as email="test0221k+staging@tt.com" which has a '+' sign in it. But this '+' sign is getting missed when I read the parameter as params[:email], i.e it is getting printed as "test0221k staging@tt.com".

'+' symbol is getting replaced with a space as you can see below. I don't know why it is happening.

Parameters: {"type"=>"ld", "email"=>"test0221k staging@tt.com", "is_combined_page"=>"true", "id"=>"-638284588"}

Why rails is over writing + with a space. How to avoid this "test0221k staging@tt.com" and get the actual email id like this "test0221k+staging@tt.com"

Can any one help me in this.

Thanks in advance.

View a post data through a comment data link not working

I'm having trouble understanding how to give a link through a comment data.

I am trying to display all the comments from the current user(but it displays it two times),if I press "view post" I'm getting an error.

What I need is , if I press a view button to take me to the corresponding post show page,that the comment belongs to

<% current_user.posts.each do |post| %>
  <% current_user.comments.each do |comment| %>
    <p>comment = <%= comment.content %></p>
    <%=link_to "View Post", post,class: "btn btn-default btn-md" %>
  <% end %>
<% end %>

jeudi 22 février 2018

How to Store the text fields array data in database without using loop using rails

I am new in ror and I am trying from 4 hours to store the data of form of textfields array like this

<input type="text" name="custom_field[names][]" class="form-control full-width" placeholder =  "Name">

<input type="text" name="custom_field[length_limit][]" class="form-control full-width" placeholder =  "Length Limit">

I want to store the arrays coming into the form in database columns of name and length limit. I don't want to use loop to do this job.

I am doing this in controller

user = CustomField.create(:name=> params[:names])

But it is giving ERROR: null value in column "name" violates not-null constraint DETAI

I am using postgresql

How can I do this?

how to show particular user created post and comment in rails

ex:i have four users: 1)userx,2)usery,3)userA,4)userB

in 4 users i want to display only userA post and comment, I'm having trouble understanding how to show a single user's created post and comments.

      post model

          belongs_to :user
          has_many :comments 

      comment model


    belongs_to :post
    belongs_to :user

       user model

    has_many :posts
    has_many :comments

     routes.rb

     resources :posts do
     resources :comments
       end

    in controllers

     def index
     @users = User.includes(:posts, :comments)
        end

     in your views:

      Views #1

     <% @users.each do |user| %>
     <% user.posts.each do |post| %>
     <%= post.post_name %>
    <%= post.post_description %>
     <% end %>

   <% user.comments.each do |comment| %>
   <%= comment.content %>
    <% end %>
   <% end %>

   Views #2:

      <% @users.each do |user| %>
   <% user.posts.each do |post| %>
     <%= post.post_name %>
      <%= post.post_description %>
      <% post.comments.each do |comment| %>
     <%= comment.content %>
    <% end %>
   <% end %>
    <% end %>

i check with this code, but it show all user data i want to show perticular user date pls help me

i ask a questions but every one say worng ans ,if i say that people down vote me pls pls help me with your ans in rails [duplicate]

This question already has an answer here:

I'm having trouble understanding to show user created post and comment pls help me stackoverflow ans

i geting ans but in ans it show all user data,but i wnt to display only user belongs to post and comment data,i don't kown people are down vote for this but it ans show all user data

post model

     belongs_to :user
     has_many :comments 

comment model

     belongs_to :post
     belongs_to :user

user model

     has_many :posts
     has_many :comments

routes.rb

resources :posts do
 resources :comments
end

in controllers

def index
  @post =  User.posts.all
  @comment = User.comments.all
end

in views index.html.erb

<%@post.each do |post|%>
  <%=post.post_name %>
  <%= post.post_description %> 
<%end%>
<%@comment.each do |comment|%>
  <%=comment.content %>
<%end%>

Little bit confusing about the array and loops in rails, so plz explain clearly

@service_center ||= []
@code2 ||= [] These two variables are declared as an array.

I have an Service_center array.

service_center[] = [<['first_array1','first_array2']>, <['second_arr1','second_arr2']

I want to Print all the elements from the array. So i am using while loop and for loop the code is here.

j=0
while !@service_center[j].nil? 
    k=0       
    @service_center[j].each do |a|
        @code2[k]= a
        k += 1
    end
j += 1
end 

so @code2 variable have [<['first_array1','first_array2']>, <['second_arr1','second_arr2'] but i print the variable it displays the second array ['second_arr1','second_arr2'].why i cant get both the array.

mercredi 21 février 2018

How to show user created post and comment in rails?

I'm having trouble understanding to show user created post and comment pls help me

i getting error in this method

undefined method `posts' for User (call 'User.connection' to establish a connection):Class

 post model

         belongs_to :user
         has_many :comments 

comment model

         belongs_to :post
         belongs_to :user

 user model

         has_many :posts
         has_many :comments

 routes.rb
          resources :posts do
           resources :comments
          end

    in controllers

  def index
          @post =  User.posts.all
          @comment = User.comments.all
   end

   in views index.html.erb

       <%@post.each do |post|%>
       <%=post.post_name %>
       <%= post.post_description %> 
           <%end%>

      <%@comment.each do |comment|%>
       <%=comment.content %>
          <%end%>

Error with rails and active admin filter, when filter 'in' is empty

how are you? I have a problem with ActiveAdmin, I have a view where I have filterts to search specific records. Like this filters:

filter :has_open_offers_in, as: :select, label: 'Has buyer offers?', collection: ['Yes', 'No'] filter :expiring_tonight_in, as: :select, label: 'Expires tonight?', collection: ['Yes', 'No']

If I filter by has_open_offers_in = 'No' and expiring_tonight_in = 'No', In my database I haven't cases with this filters, then when I filter with this params do a query in postgres with this: ("bid_sales"."id" IN (A LOT OF IDS) AND "bid_sales"."id" IN ()) but postgres throw an error because don't support a IN ()

Postgres error example:

postgres=# select * from customer where customer_id in (); ERROR: syntax error at or near ")"

someone view similar error?

overriding the functionality of cancel button of X-editable(rails)

I have used the x-editable for my in place edit functionality.
https://vitalets.github.io/x-editable/docs.html.

I want to add a delete(my own) functionality in the cancel code button.

<%= link_to "Delete", {controller: "questionnaires", action: "destroy", id: question.id , client_id: @selectedClientId, label: question.label {class: 'table',method: :delete} %>

How to achieve that. I am not able to figure it out. Any help would be highly appreciated

mardi 20 février 2018

rescue / exeception marked as red in editor? Were Am I going wrong

I have just started test automation project in ruby, however, am only used to java so trying to get the hang of ruby and I cant see where my syntax is going wrong.

rescue Watir::Exception::TimeOutException => e

is underlined in red, why? Unexpected keyword rescue?

   def check(UpTimer)
        limit = 0
      begin
     @browser.alert.wait_until_present(UpTimer)
     if code
      code
      rescue Watir::Exception::TimeOutException => e
       limit += 1
       retry if limit <= 3
       #Add in Message for HTML Report?
     end
  end
end

in place edit in rails for textbox

I have an application, in which I have textboxes, how to do in-place edit I tried all, I am getting nothing and I am not able to set up as per guides of GitHub

https://github.com/bootstrap-ruby/bootstrap-editable-rails

https://github.com/janv/rest_in_place

and best_in_place doesn't work for higher rails version

<input type="text" name="<%= 'commit['+ question.id+']' %>" id =        
   "showAnswer" placeholder="Your answer"  class="form-name form-
   control" value = "<%=  !@tempDisplay.nil? ? @tempDisplay.key?
   (question.id) ? @tempDisplay[question.id] :'' : '' %>" 
   style="margin-bottom:4px;">  

 <button name ="btn"  type="button" class="tabledit-edit-button btn 
  btn-sm btn-default"  value = "Save"  onclick='singleSave("<%= 
  question.id %>")'> Save</button>

this is my text field in which I want to apply-in-place edit functionality but how to achieve that functionality without using my Save button as my save button call ajax function and passes parameters to the controller and how to use in_place edit in my text box.As my text acts as to display text also.When the user enters text in the textbox it should become non-textbox and when he/she clicks on it, it becomes editable

How to apply in place edit in my text box, it also send params to the controller as an array via name="<%= 'commit['+ question.id+']' %>"

can anyone tell me how to do that, as I am not able to follow the GitHub instructions as its vague for me

lundi 19 février 2018

Rails can't convert Hash into Integer

After setup the current_user

def current_user
    @current_user ||= User.first(conditions: ['auth_token = :token or oauth_token = :token', { token: cookies[:auth_token] }]) if cookies[:auth_token]
  end

rails raised

can't convert Hash into Integer

This method was working in rails 3 now on rails 5 raised this, someone can spare a hint about this issue?

When use OR in ruby? [duplicate]

This question already has an answer here:

After setup the current_user with the standard session, would be great if the user log in with cookie or api token. so the utilization of the OR seems required.

def current_user
    token = User.find_by(cookies[:auth_token]) or params[:api_token] 
    @current_user ||= token if cookies[:auth_token]
  end

i've added the or against the find_by

SQLite3::SQLException: unrecognized token: "9C46LFbm3Mzn1K6iA4HwdQ": SELECT "users".* FROM "users" WHERE (9C46LFbm3Mzn1K6iA4HwdQ) LIMIT ?

and the db raised this exception, that seems not related with the function so my doubt is if OR can be used with find_by ir just with where?

undefined method `[]' for nil:NilClass(path)

I am beginner in Ruby who's looking to debug an issue in my "index" view. I am trying to list out different values for dataset. However, I am not sure where the issue lies in the following line of code.

 <% @datasets.each do |dataset| %>
   <%= Dir[File.join(dataset.ds.path[0,dataset.ds.path.to_s.length-4], '**', '*')].count
  <% end %>

How to pass extra params inside option hash in confirmation email in Rails?

I am trying to pass extra params inside the options{} hash in the confirmation email but It is just showing me subject and from headers in the mailer. This is my code

CustomMailer.confirmation_instructions(user,token, {custom_param: "abc"})

When I show opts data inside template like this

@first_name = opts

It shows

{:subject=>"Email Confirmation", :from=>"no-reply@sample.com"}

why it is not working?

any help?

Rails Stub a variable inside module

Module Foo
 def querying_result(criteria)
  User.find_by_account(current_account).where(criteria: criteria)
 end
end

I write a unit test for the above module and want to stub current_account variable which is coming from application controller.

I tried with following

Foo.stubs(current_account: @user.account).returns(@user.account)
Foo.any_instance.stub(current_account:@user.account).and_return(@user.account)

My Test file

class FooTest << ActiveSupport::TestCase
context "querying the result"
  setup do
   @user = User.first
  end
  should "return all users" do
    users = querying_result(criteria)
    assert_equal users.count, 1
  end
end

what am I missing here. Kindly help

How to refresh the browser using watir in cucumber rails

I am using ruby 2.3.1p112, Rails 5.1.5 version I do a automation testing with gem 'watir' I need to refresh the browser in my script So I add the below code

browser.refresh

But there is no action done on this command

Several Charts in one page chartJs

I'm developing a form generator with RoR and I want to draw multiple charts in one result page (one chart for one question).

For the moment I'm doing it statically in my controller:

Controller :

    @polls5 = @polls.where(question_id: 5).group("nom")
    @polls7 = @polls.where(question_id: 7).group("nom")
   ...

View

 <canvas id="myChart" ></canvas>


<script>
var ctx = document.getElementById("myChart").getContext('2d');


labels= [<% for rep in @polls7 %>
     "<%= rep.nom %>",
    <% end %>];

i =<%= @polls7.count.values %>;


var myChart = new Chart(ctx, {
type: 'bar',
data:  {
    labels:labels,
    datasets: [{
        label: '',
        data: i,
        backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            'rgba(255, 206, 86, 0.2)',
            'rgba(75, 192, 192, 0.2)',
            'rgba(153, 102, 255, 0.2)',
            'rgba(255, 159, 64, 0.2)'
        ],
        borderColor: [
            'rgba(255,99,132,1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            'rgba(75, 192, 192, 1)',
            'rgba(153, 102, 255, 1)',
            'rgba(255, 159, 64, 1)'
        ],
        borderWidth: 1
    }]
},
options: {
    scales: {
        yAxes: [{
            ticks: {
                beginAtZero:true
            }
        }]
    }
}
});

How can I loop for every local variable @polls2, @polls3, etc (I've read that we can't loop to create local variable in Ruby) and how can I loop in my JS script to draw my charts.

Thank you

dimanche 18 février 2018

dynamically adding button based on my label text database column in rails

I have a rails app, in which I want to add buttons dynamically based on my label text in the database.I have a questionnaire schema and it contains label column with various kind of label i.e, PERSONAL STYLE,STYLING,WARDROBE. My UI should automatically add buttons for each label column value i.e. if it contains 3 label in label column then it should add dynamically 3 buttons with PERSONAL STYLE,STYLING,WARDROBE written on it. And on clicking those button , these label specific question must show in UI.

Here is the image for the UI User Interface(UI) for above

My schema is like this with 3 columns. Questionnaire Model which has questionnaire table with these schema
id , label , question

When i click on STYLING button, STYLING labeled questions from database should show in UI.
How to achieve that. Currently I am able to load all questions from database.But I have to now show label specific questions on the UI on clicking the label buttons.

here my html.erb code

<% @questionnaire.each do |question| %>
<label> <%= question.label %></label>
<h2> <%= question.text %></h2>
<% end %>

code in controller

 @questionnaire = Questionnaire.all

Every suggestions would be much appreciated.

If any substring in a string contains the required regex

mailto:abcd@gmail.com wont match the email regex. /\A[\w+-.]+@[a-z\d-]+(.[a-z\d-]+)*.[a-z]+\z/i I want to check if any substring in the given string matches the regex. In this case, abcd@gmail.com matches the regex.

samedi 17 février 2018

Ruby When use and pass parameters to functions?

I would like to redirect the user in the authetication method if the request format is html or json, but always just show as the json format has been requested.

I've passed the (html and json) as parameters! Someone know if this is the right way to pass the parameters?

def authenticate_user!(html,json)
    if request.format.html? && current_user.nil? 
      redirect_to login_url, notice: "Not authorized" 
    else 
       request.format.json? && current_user.nil? 
      redirect_to download_url, notice: "you need download the file first"

    end

  end

vendredi 16 février 2018

How does RVM pick where to find the gem

I noticed that rvm has more than one directory for saving 2.3.0 gems.

/usr/share/rvm/gems/ruby-2.3.0/gems

/usr/share/rvm/rubies/ruby-2.3.0/lib/ruby/gems/2.3.0/gems

I want to understand how RVM decides which directory to use. I have this gem rspec_junit_formatter that does not work with bundler newer than 1.12.5 I get different behavior when the rspec task is defined in lib/tasks/rspec.rake file as opposed to the rspec task defined in a Rakefile in ruby non-rails projects.

In rails rvm picks bundler from the rvm/gems directory. In plain ruby rvm picks bundler from the rubies directory. How come?

How to remove Failed to create chart: can't acquire context from the given item error while using it with Ruby on Rails?

I installed frappe charts for ruby on rails through gem.

Then I tried to run one of the frappe-chart code which is given in their website:

 let data = {
    labels: ["12am-3am", "3am-6am", "6am-9am", "9am-12pm",
      "12pm-3pm", "3pm-6pm", "6pm-9pm", "9pm-12am"],

    datasets: [
      {
        title: "Some Data",
        values: [25, 40, 30, 35, 8, 52, 17, -4]
      },
      {
        title: "Another Set",
        values: [25, 50, -10, 15, 18, 32, 27, 14]
      },
      {
        title: "Yet Another",
        values: [15, 20, -3, -15, 58, 12, -17, 37]
      }
    ]
  };

  let chart = new Chart({
    parent: "#chart", // or a DOM element
    title: "My Awesome Chart",
    data: data,
    type: 'bar', // or 'line', 'scatter', 'pie', 'percentage'
    height: 250,

    colors: ['#7cd6fd', 'violet', 'blue'],
    // hex-codes or these preset colors;
    // defaults (in order):
    // ['light-blue', 'blue', 'violet', 'red',
    // 'orange', 'yellow', 'green', 'light-green',
    // 'purple', 'magenta', 'grey', 'dark-grey']

    format_tooltip_x: d => (d + '').toUpperCase(),
    format_tooltip_y: d => d + ' pts'
  });
<canvas id="note-graph"></canvas>

I also tried with div instead of canvas but it's always showing the same error.

Refresh database (mySql) using jquery rails

I am trying to read data from mysql database, it is basically the pincode and comparing it with the near location.

I need to check the database every 2 secs for new records without refreshing my page in my rails application. Is there any possibility.

jeudi 15 février 2018

Is it possible in paperclip to delete the original image and reprocess! on the default style

Is it possible in paperclip to delete the original image (or keep it somewhere) and make reprocess! on the default style that we set

how can i test my job model and what are the missing things

Models/job.rb

class Job < ApplicationRecord
    belongs_to :user
    belongs_to :category
  belongs_to :company
  accepts_nested_attributes_for :company

  has_attached_file :image, styles: {  medium: "800x800>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
  validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/
  validates :title, presence: true
  validates :title, length: {minimum: 5, maximum: 35}
  validates :description,length: {minimum: 10, maximum: 400}, presence: true

require 'rails_helper'

rspec/models/job_spec.rb

RSpec.configure do |config|
  config.include(Shoulda::Matchers::ActiveModel, type: :model)
  config.include(Shoulda::Matchers::ActiveRecord, type: :model)
end

RSpec.describe Job, type: :model do

      it { should belong_to(:user) }
      it { should belong_to(:category) }
      it { should belong_to(:company) }
      it { is_expected.to validate_presence_of(:title) }
      it { is_expected.to validate_presence_of(:description) }
      it { should accept_nested_attributes_for(:company) }
      it { should validate_length_of(:description).is_at_least(10) }
      it { should validate_length_of(:description).is_at_most(400) }
      it { should validate_length_of(:title).is_at_least(5) }
      it { should validate_length_of(:title).is_at_most(35) }
      it { should have_db_column(:user_id) }
      it { should have_db_column(:title) }
      it { should have_db_column(:description) }
      it { should have_db_column(:jobclosedate) }
      it { should have_db_column(:company) }
      it { should have_db_column(:id) }
      it do
                 should allow_value('2013-01-01').
                   for(:jobclosedate).
                  on(:create)
              end
end

i'm used to test job model(rspec), i write few unit test scenario for job models. what are the missing things that i need to add. could you please help me to write better unit test using rspec.

mercredi 14 février 2018

how to check if certain key exists in array of object json ruby on rails

how to check if a particular key exists or not in my json which is an array of objects in my controller this is my json

[{"question"=>"0a2a3452", "answer"=>"bull"}, {"question"=>"58deacf9", "answer"=>"bullafolo"}, {"question"=>"32c53e5f", "answer"=>"curosit"}, {"question"=>"b5546bcf", "answer"=>""}, {"question"=>"0f0b314", "answer"=>""}]

I tried looping through the json array, but this is tedious, as I need to check that if that json has that particular key in "if" condition

Thank you in advance any help would be highly appreciated

mardi 13 février 2018

read a file and find if a string exists and return the tablename

I am trying to read a file, if the file has 'alter table' then it has to search for 'modify' if modify exists then it has to return the table name. For that i wrote the below code and it worked.

filename='modify_table.sql'
bol1="false"
File.foreach(filename).with_index do |line, line_num|

#convert all characters to upper case
 if ( line =~ /[a-z]/ )
 line = line.upcase
 end
  if (line =~ /ALTER TABLE/) 

    location = line.index("ALTER TABLE") + 11
    subline = line[location..-1]
    sublineParts = subline.split(" ")
    tableName = sublineParts[0]

    bol1 = line.include?("MODIFY")
    if (bol1)
    puts " found modify column on #{tableName}"
  else
    puts " no modify found"
  end
end
end

My file contains:

begin
BEGIN EXECUTE IMMEDIATE 'alter table schemaname.tablename 
modify (
abc              VARCHAR2(200 BYTE),
xyz               VARCHAR2(200 BYTE)
)'; EXCEPTION when others then if (SQLCODE != -01430 and SQLCODE != -942) then RAISE; end if; END;
end;
/

if alter and modify are on the same line my code works. In the above file, both are in diff line. so the code i wrote returns no modify found even if there is a modify in the file. Can someone help me how I could read the next line and find modify

i have issue rspec syntax

job model
class Job < ApplicationRecord
    belongs_to :user
    belongs_to :category
  belongs_to :company
  accepts_nested_attributes_for :company


  has_attached_file :image, styles: {  medium: "800x800>", thumb: "100x100>" }, default_url: "/images/:style/missing.png"
  validates_attachment_content_type :image, content_type: /\Aimage\/.*\z/

  validates :title, presence: true
  validates :title, length: {minimum: 5, maximum: 15}
  validates :description,length: {minimum: 10, maximum: 400}
job_spec.rb
RSpec.describe Job, type: :model do
  it "ensures title presence" do
    # job=Job.new(title:'software engineer').save
    expect(job).to validate_presence_of(:title)

  end


end

i'm new to ruby, actually i want to write unit test using rspec to model. i want to write testing for association as well, but i don't know how to start.can any one help me to sort this out.

Stop code execution if file is missing

I use this code in order to load configuration file. How I can stop code execution if line in file configuration is missing?

def load_environment_config(gateway, trx_type)
    @config = YAML.load_file("config/#{env}_config.yml")["#{env.upcase}"]
    puts "\nMissing gateway configuration for #{gateway} in file config/#{env}_config.yml!\n\n" unless @config[gateway]
  end

lundi 12 février 2018

mysql2 Gem::Ext::BuildError: ERROR: Failed to build gem native extension

When i download the rails application from github https://github.com/ari/jobsworth An then give bundle install it throws error

Gem::Ext::BuildError: ERROR: Failed to build gem native extension.
An error occurred while installing mysql2 (0.4.4), and Bundler cannot continue.
Make sure that `gem install mysql2 -v '0.4.4'` succeeds before bundling.

after I give the sudo gem install mysql2 -v '0.4.4' and it displays like

Fetching: mysql2-0.4.4.gem (100%)
Building native extensions.  This could take a while...
ERROR:  Error installing mysql2:
    ERROR: Failed to build gem native extension.

    current directory: /var/lib/gems/2.4.0/gems/mysql2-0.4.4/ext/mysql2
/usr/bin/ruby2.4 -r ./siteconf20180212-10708-v1q8lj.rb extconf.rb
mkmf.rb can't find header files for ruby at /usr/lib/ruby/include/ruby.h

extconf failed, exit code 1

Gem files will remain installed in /var/lib/gems/2.4.0/gems/mysql2-0.4.4 for inspection.
Results logged to /var/lib/gems/2.4.0/extensions/x86_64-linux/2.4.0/mysql2-0.4.4/gem_make.out

after run bundle install it throws same error

dimanche 11 février 2018

Fetch id of selected option in dropdown in controller

I have a model named 'Assessment':

class Assessment < ApplicationRecord
  has_many :assessment_students
  has_many :students, through: :assessment_students
end

Join table is:

class AssessmentStudent < ApplicationRecord
  belongs_to :student
  belongs_to :assessment
end

There is another model:

class Classroom < ApplicationRecord
 has_many :classroom_students
 has_many :students, through: :classroom_students
 has_many :assessments
end

In show,html.erb of classrooms, I have a dropdown which shows all assessments (generated from assessment table).

Code is:

<%= collection_select(:assessment :assessment_id, Assessment.all, :id, :assessment_name , :prompt => true) %>

Requirement of the project is: Based on the assessment chosen by the user in the show.html.erb page, we have to show all students details like name etc assigned to that particular assessment. I have stored this data in join table 'AssessmentStudent '. However, I am not sure how to pass id from the above collection_select to classroom controller. I have below code:

show.html.erb:

<%= collection_select(:assessment :assessment_id, Assessment.all, :id, :assessment_name , :prompt => true) %>

<div id="divResult">
 <% @assessmentstudents1.each do |t| %>
      <% t.assessment_students.each do |record| %>
        <%= record.student_id %>
     <% end %>  
   <% end %>  
</div>

classroom controller:

def show
   @assessmentstudents1 = Assessment.find(params[:assessment][:assessment_id]).preload(:assessment_students)
end

def classroom_params
  params.require(:classroom).permit(:classroom_name, :classroom_year, :customer_id, :classroom_student, :student_ids => [])
  params.require(:assessment).permit(:assessment_id)
end

samedi 10 février 2018

Rails: how to join two models through two different relations?

I have two models: Saft (a magazine) and Keyword. Each "Saft" is defined by a series of keywords, but also has a title, which is always one of its keywords. The Saft and Keyword models are connected through a HABTM join table in order to pull all the keywords and now I am trying to pull the title from the keywords table onto the saft/show.html.erb, too. I am trying to use the class_name option in order to pull the title. Therefore I created the Edition model.

class Saft < ActiveRecord::Base
  attr_accessible :colour, :cover_alt, :description, :number, :short
  has_and_belongs_to_many :keywords, :join_table => "safts_keywords"
  has_one :title, :through => :edition, :class_name => "keyword"
  has_one :edition
end

class Keyword < ActiveRecord::Base
  attr_accessible :word, :description
  has_and_belongs_to_many :safts, :join_table => "safts_keywords"
  belongs_to :issue, :through => :edition, :class_name => "saft"
end

class Edition < ActiveRecord::Base
  attr_accessible :saft_id, :keyword_id
  belongs_to :saft
  belongs_to :keyword
end

class SaftsController < ApplicationController 
  def show
    @saft = Saft.find(params[:id])
  end

show.html.erb
    <%= @saft.title.upcase %>

I get the following error:

Started GET "/safts/2" for 127.0.0.1 at Sat Feb 10 17:31:28 +0100 2018
Connecting to database specified by database.yml
Processing by SaftsController#show as HTML
  Parameters: {"id"=>"2"}
  Saft Load (1.8ms)  SELECT `safts`.* FROM `safts` WHERE `safts`.`id` = ? LIMIT 1  [["id", "2"]]
  Image Load (0.3ms)  SELECT `images`.* FROM `images` WHERE `images`.`saft_id` = 2
  Rendered safts/show.html.erb within layouts/public (35.0ms)
Completed 500 Internal Server Error in 103ms

ActionView::Template::Error (uninitialized constant Saft::keyword):
    29:                 </div>
    30:                 <div class="saft_box col-content">
    31:                     <div class="saft_keyword">
    32:                         <strong><%= @saft.title.upcase %></strong>
    33:                     </div>
    34:                     <div class="saft_description">
    35:                         <p><%= @saft.description %></p>
  app/views/safts/show.html.erb:32:in `_app_views_safts_show_html_erb___758994895_2167416580'

How can I get this working?

C:/Ruby23-x64/lib/ruby/2.3.0/fileutils.rb:253:in `mkdir': Invalid argument

when i was try to use rails g rspec:install , it will display above error. how may solve this issue? could you please sort this out.

rails g rspec:install create .rspec create spec C:/Ruby23-x64/lib/ruby/2.3.0/fileutils.rb:253:in mkdir': Invalid argument @ dir_s_mkdir - C:/Users/Anuradha-PC/Desktop/Ruby/Jobs_board2/spec/C: (Errno::EINVAL) from C:/Ruby23-x64/lib/ruby/2.3.0/fileutils.rb:253:infu_mkdir' from C:/Ruby23-x64/lib/ruby/2.3.0/fileutils.rb:227:in block (2 levels) in mkdir_p' from C:/Ruby23-x64/lib/ruby/2.3.0/fileutils.rb:225:inreverse_each' from C:/Ruby23-x64/lib/ruby/2.3.0/fileutils.rb:225:in block in mkdir_p' from C:/Ruby23-x64/lib/ruby/2.3.0/fileutils.rb:211:ineach' from C:/Ruby23-x64/lib/ruby/2.3.0/fileutils.rb:211:in mkdir_p' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/actions/create_file.rb:62:inblock in invoke!' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/actions/empty_directory.rb:117:in invoke_with_conflict_check' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/actions/create_file.rb:60:ininvoke!' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/actions.rb:94:in action' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/actions/create_file.rb:25:increate_file' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/actions/file_manipulation.rb:26:in copy_file' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/actions/directory.rb:94:inblock in execute!' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/actions/directory.rb:80:in each' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/actions/directory.rb:80:inexecute!' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/actions/directory.rb:66:in invoke!' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/actions.rb:94:inaction' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/actions/directory.rb:52:in directory' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/rspec-rails-3.7.2/lib/generators/rspec/install/install_generator.rb:23:inblock in copy_spec_files' from C:/Ruby23-x64/lib/ruby/2.3.0/tmpdir.rb:89:in mktmpdir' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/rspec-rails-3.7.2/lib/generators/rspec/install/install_generator.rb:20:incopy_spec_files' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/command.rb:27:in run' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/invocation.rb:126:ininvoke_command' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/invocation.rb:133:in block in invoke_all' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/invocation.rb:133:ineach' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/invocation.rb:133:in map' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/invocation.rb:133:ininvoke_all' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/group.rb:232:in dispatch' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/base.rb:466:instart' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/generators.rb:269:in invoke' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/commands/generate/generate_command.rb:24:inperform' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/command.rb:27:in run' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/invocation.rb:126:ininvoke_command' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor.rb:387:in dispatch' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/command/base.rb:63:inperform' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/command.rb:44:in invoke' from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/commands.rb:16:in' from bin/rails:4:in require' from bin/rails:4:in'

when i was try to use rails g rspec:install , it will display above error. how may solve this issue? could you please sort this out.

vendredi 9 février 2018

Is there a way to keep POSTed XML in tact in Ruby on Rails?

I have a REST API in my Rails app that users will be posting XML to. I know that Rails (perhaps Rack in this case) converts the posted data to a params hash.

I'm curious if there's a way to get Rails to not convert the XML to a params hash? Instead, I'd like to get the XML as a string.

about ruby on rails association

when i use belongs_to association in rails, the the foreign which is automatically generated or i have to add that column first in the schema and then use association

class ClientQuestionnaire < ActiveRecord::Base
  belongs_to :question , :class_name => 'Questionnaire'    
end





class Questionnaire < ActiveRecord::Base

  has_many :client_questionnaires

end

Do i have to make question_id first in client_questionnaires table and then use belongs_to :question , :class_name => 'Questionnaire' statement in my model

WARN: Unresolved specs during Gem::Specification.reset:

C:\Users\Anuradha-PC\Desktop\Ruby\Jobs_board2>rails g rspec:install Looks like your app's ./bin/rails is a stub that was generated by Bundler.

In Rails 5, your app's bin/ directory contains executables that are versioned like any other source code, rather than stubs that are generated on demand.

Here's how to upgrade:

bundle config --delete bin # Turn off Bundler's stub generator rails app:update:bin # Use the new Rails 5 executables git add bin # Add bin/ to source control

You may need to remove bin/ from your .gitignore as well.

When you install a gem whose executable you want to use in your app, generate it and add it to source control:

bundle binstubs some-gem-name git add bin/new-executable

WARN: Unresolved specs during Gem::Specification.reset:
      i18n (~> 0.7)
      minitest (~> 5.1)
      rack (~> 2.0)
      rack-test (>= 0.6.3)
      nokogiri (>= 1.5.9, >= 1.6)
      rake (>= 0.8.7)
      method_source (>= 0)
WARN: Clearing out unresolved specs.
Please report a bug if this causes problems.
      create  .rspec
      create  spec
C:/Ruby23-x64/lib/ruby/2.3.0/fileutils.rb:253:in `mkdir': Invalid argument @ dir_s_mkdir - C:/Users/Anuradha-PC/Desktop/Ruby/Jobs_board2/spec/C: (Errno::EINVAL)
        from C:/Ruby23-x64/lib/ruby/2.3.0/fileutils.rb:253:in `fu_mkdir'
        from C:/Ruby23-x64/lib/ruby/2.3.0/fileutils.rb:227:in `block (2 levels) in mkdir_p'
        from C:/Ruby23-x64/lib/ruby/2.3.0/fileutils.rb:225:in `reverse_each'
        from C:/Ruby23-x64/lib/ruby/2.3.0/fileutils.rb:225:in `block in mkdir_p'
        from C:/Ruby23-x64/lib/ruby/2.3.0/fileutils.rb:211:in `each'
        from C:/Ruby23-x64/lib/ruby/2.3.0/fileutils.rb:211:in `mkdir_p'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/actions/create_file.rb:62:in `block in invoke!'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/actions/empty_directory.rb:117:in `invoke_with_conflict_check'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/actions/create_file.rb:60:in `invoke!'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/actions.rb:94:in `action'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/actions/create_file.rb:25:in `create_file'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/actions/file_manipulation.rb:26:in `copy_file'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/actions/directory.rb:94:in `block in execute!'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/actions/directory.rb:80:in `each'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/actions/directory.rb:80:in `execute!'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/actions/directory.rb:66:in `invoke!'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/actions.rb:94:in `action'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/actions/directory.rb:52:in `directory'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/rspec-rails-3.7.2/lib/generators/rspec/install/install_generator.rb:23:in `block in copy_spec_files'
        from C:/Ruby23-x64/lib/ruby/2.3.0/tmpdir.rb:89:in `mktmpdir'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/rspec-rails-3.7.2/lib/generators/rspec/install/install_generator.rb:20:in `copy_spec_files'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/command.rb:27:in `run'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/invocation.rb:126:in `invoke_command'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/invocation.rb:133:in `block in invoke_all'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/invocation.rb:133:in `each'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/invocation.rb:133:in `map'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/invocation.rb:133:in `invoke_all'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/group.rb:232:in `dispatch'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/base.rb:466:in `start'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/generators.rb:269:in `invoke'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/commands/generate/generate_command.rb:24:in `perform'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/command.rb:27:in `run'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor/invocation.rb:126:in `invoke_command'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/thor-0.20.0/lib/thor.rb:387:in `dispatch'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/command/base.rb:63:in `perform'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/command.rb:44:in `invoke'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/commands.rb:16:in `<top (required)>'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/app_loader.rb:46:in `require'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/app_loader.rb:46:in `block in exec_app'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/app_loader.rb:35:in `loop'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/app_loader.rb:35:in `exec_app'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.1.4/lib/rails/cli.rb:5:in `<top (required)>'
        from C:/Ruby23-x64/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:127:in `require'
        from C:/Ruby23-x64/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:127:in `rescue in require'
        from C:/Ruby23-x64/lib/ruby/2.3.0/rubygems/core_ext/kernel_require.rb:40:in `require'
        from C:/Ruby23-x64/lib/ruby/gems/2.3.0/gems/railties-5.1.4/exe/rails:9:in `<top (required)>'
        from C:/Ruby23-x64/bin/rails:22:in `load'
        from C:/Ruby23-x64/bin/rails:22:in `<main>'

how may i solve this issue?, could you please help me to sort out this issue

jeudi 8 février 2018

Unpermitted parameter: :companies

class CreateJobs < ActiveRecord::Migration[5.1]
  def change
    create_table :jobs do |t|
      t.string :title
      t.text :description
      t.string :c_name
      t.integer :user_id
      t.integer :company_id
      t.timestamps
    end
  end
end

class CreateCompanies < ActiveRecord::Migration[5.1]
  def change
    create_table :companies do |t|
      t.string :c_name
      t.text :c_description
      t.integer:user_id
      t.timestamps
    end
  end
end

# Models
class User < ApplicationRecord
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  has_many :companies
  has_many :jobs
end

class Job < ApplicationRecord
  belongs_to :user
  belongs_to :category
  belongs_to :company
end

class Company < ApplicationRecord
  belongs_to:user
  has_many:jobs

end

# Jobs controller
def show
  end

  def new

    @job = current_user.jobs.build       
  end

  def create

        job_attrs = jobs_params.except(:company_id)
        company = Company.find_by_user_id(current_user.id)
        job_attrs = Company.find_by(user_id: jobs_params[:company_id])
       if job_attrs
    @job = current_user.jobs.build(job_attrs)

    if @job.save
      flash[:success]= "success"
      redirect_to @job

      else

      flash[:error]=@job.errors.full_messages
      render "new"
      end
    end

    def jobs_params
      params.require(:job).permit(:title, :description, :c_name, :category_id, :image,:jobclosedate,:company_id)
    end`enter code here`

when this happened company user log the system and try to create a job,

Processing by JobsController#create as HTML Parameters: {"utf8"=>"✓", "authenticity_token"=>"PE5K1+5jBCbS8DBAmF1uQBii3QmuAqBJ0Wg89mwO9Y/jMCbTVON8yhpEBL88XLyJRhJr3aZ/ZLDOnDrv0bcdng==", "job"=>{"title"=>"job job", "description"=>"hhhhhh jjjjjjjjjj", "companies"=>{"c_name"=>""}, "category_id"=>"1", "jobclosedate"=>""}, "commit"=>"Create Job"}

Unpermitted parameter: :companies [1m[36mCompany Load (0.5ms)[0m [1m[34mSELECT "companies".* FROM "companies" WHERE "companies"."user_id" = ? LIMIT ?[0m [["user_id", 1], ["LIMIT", 1]] Unpermitted parameter: :companies [1m[36mCompany Load (3.5ms)[0m [1m[34mSELECT "companies".* FROM "companies" WHERE "companies"."user_id" IS NULL LIMIT ?[0m [["LIMIT", 1]] No template found for JobsController#create, rendering head :no_content Completed 204 No Content in 1839ms (ActiveRecord: 9.0ms)"

mercredi 7 février 2018

parameters will not pass in the child class

when i'm try to create a job, it will show company must exit, c_name and company_id will not pass in the views/jobs/_form
class CreateJobs < ActiveRecord::Migration[5.1] def change create_table :jobs do |t| t.string :title t.text :description t.string :c_name t.integer :user_id t.integer :company_id t.timestamps end end end

    class CreateCompanies < ActiveRecord::Migration[5.1]
      def change
        create_table :companies do |t|
          t.string :c_name
          t.text :c_description
          t.integer:user_id
          t.timestamps
        end
      end
    end

    # Models
    class User < ApplicationRecord
      # Include default devise modules. Others available are:
      # :confirmable, :lockable, :timeoutable and :omniauthable
      devise :database_authenticatable, :registerable,
             :recoverable, :rememberable, :trackable, :validatable

      has_many :companies
      has_many :jobs
    end

    class Job < ApplicationRecord
        belongs_to :user
        belongs_to :category
        belongs_to :company
    end

    class Company < ApplicationRecord
        belongs_to:user
        has_many:jobs

    end

    # Jobs controller
    def show
            end

            def new

                   @job = current_user.jobs.build       
            end

    def create
            job_attrs = jobs_params.except(:c_name)
            job_attrs[:c_name] = Company.find_by(id: jobs_params[:c_name])
            @job = current_user.jobs.build(job_attrs)

          if @job.save
            flash[:success]= "success"
            redirect_to @job

            else

            flash[:error]=@job.errors.full_messages
            render "new"
            end
        end

    def jobs_params
                params.require(:job).permit(:title, :description, :c_name, :category_id, :image,:jobclosedate,:company_id)
    end
in the jobs/_form
  <%= simple_form_for(@job,validation:true ,html: { mutlipart: true, class: 'form-horizontal'}) do |f| %>
<%= f.input :title, label: "Job Title", input_html: { class: "form-control"}%>
<%= f.input :description, label: "Job Description", input_html: { class: "form-control" }%>
<%= f.input :c_name, label: "Your Company", input_html: { class: "form-control" }%>
<%= f.collection_select :category_id,Category.all, :id, :name, {promt: "Choose a category" }%>

when i'm try to create a job, it will show company must exit, c_name and company_id will not pass in the views/jobs/_form . could you please help me to sort it out.it's seems create def has issue. i'm new to ruby please explain me to sort this out.

program to find next highest number for the given number which should contains only the digits 2 and 7

program to find next highest number for the given number which should contains only the digits 2 and 7 **

example: 
a) Input is 2 Output is 7

b) Input is 22 Output is 27

c) Input is 423 Output is 722

**

Error: `getwd` : No such file or directory - getcwd?

Can you anyone help me how to solve this problem

gems/bundler-1.16.0.pre.3/lib/bundler/shared_helpers.rb:71:in `getwd': No such file or directory - getcwd (Errno::ENOENT)

mardi 6 février 2018

How to seed join table data from yaml file through seed.rb in Rails

I am trying to add to my seed.rb the ability to load data onto a join table for my ROR 3.2.5 application.

I have two models: Saft.rb and Keyword.rb, which I would like to join.

class Saft < ActiveRecord::Base
   has_and_belongs_to_many :keyword, :join_table => "safts_keywords"
end

class Keyword < ActiveRecord::Base
  attr_accessible :word
  has_and_belongs_to_many :saft, :join_table => "safts_keywords"
end

I seed datasets for both from a yaml file, such as from: keywords_list.yml

---
  - word: "12"

  - word: "34"

The corresponding part of my Seed.rb:

keywords_data = YAML.load_file(Rails.root.join('db/seeds/keywords_list.yml'))
keywords_data.each do |keyword|
    h = Keyword.find_or_initialize_by_word(keyword['word'])
    h.save
end

Now I would like to seed the initial dataset for the join table from a yaml file too. (safts_keywords.yml)

---
  - saft_id: 1
    keyword_id: 2

When I try to load the data through:

# Load the Join Table
safts_keywords_data = YAML.load_file(Rails.root.join('db/seeds/safts_keywords_list.yml'))
safts_keywords_data.each do |saftkeyword|
    h = SaftKeyword.find_or_initialize_by_saft_id(saftkeyword['saft_id'], 
    :keyword_id => saftkeyword['keyword_id'])
    h.save
end

I get:

.
.
.
** Invoke db:structure:load_if_sql (first_time)
** Invoke db:create
** Execute db:structure:load_if_sql
** Invoke db:seed (first_time)
** Execute db:seed
** Invoke db:abort_if_pending_migrations (first_time)
** Invoke environment
** Execute db:abort_if_pending_migrations
rake aborted!
uninitialized constant SaftKeyword
/Users/Stephan/Development/REPRO/saftzine_com/db/seeds.rb:99
/Users/Stephan/Development/REPRO/saftzine_com/db/seeds.rb:97:in `each'
/Users/Stephan/Development/REPRO/saftzine_com/db/seeds.rb:97
.
.
.

How can I get this to work?

Routing Error when creating new html.erb file in views no route matches wrong controller

No route matches {:controller=>"persons", :locale=>:de}

I want simple page with just text which I call info.html.erb. I saved it in app/views/projects.

My projects_controller looks like this

def info
end

My rake routes looks like this

info_projects GET    /projects/info(.:format)   projects#info

My routes.rblooks like this

resources :projects do
 collection do
 get :info
 end
 ...
end

The view with the link_to the info is the index.html.erb in app/views/projects and looks like this

<%= link_to t(:create_new_project), info_projects_path %>)

When I click the link I get the ERROR above. I have no idea what it has to do with persons? I just want the empty page to be displayed so that I can code the info page.

Thank you in advance =)

vendredi 2 février 2018

Trying to unzip a 600mb tgz with ruby gives out of integer range error

Trying to untar a tgz file... with the following code:

tar_extract.each do |entry|
  entry_filename = File.basename(entry.full_name)
  next if entry.directory? # don't unzip directories
  next if !entry.file? # if it's not a file skip  
  next if entry.full_name.starts_with?('/') # another check

  file_path = File.join(working_directory, entry_filename)
  puts "Writing file: #{file_path}"

  File.open(file_path, 'wb') do |f|
    f.write(entry.read)
  end

  bytes = File.size(file_path)

  puts "Successfully wrote file with #{bytes} bytes"
end

tar_extract.close

This code usually works successfully, however when the file within the TGZ is too big, I get a integer out of range error.

Writing file: /files/working_dir/test1.tar.gz  
Successfully wrote file with 244704472 bytes 

Writing file: /files/working_dir/test2.sql
RangeError: integer 2556143960 too big to convert to `int'
from /usr/local/rvm/rubies/ruby-2.1.1/lib/ruby/site_ruby/2.1.0/rubygems/package/tar_reader/entry.rb:126:in `read'

I'm not sure what else I should try.

Looking at the ruby source, this is the code block:

  ##
  # Reads +len+ bytes from the tar file entry, or the rest of the entry if
  # nil

  def read(len = nil)
    check_closed

    return nil if @read >= @header.size

    len ||= @header.size - @read
    max_read = [len, @header.size - @read].min

    ret = @io.read max_read
    @read += ret.size

    ret
  end

Words length in Faker

How to generate array of words of specific length from Faker gem in rails? For example I would like to make an array of five words, where each word's length is also five.

jeudi 1 février 2018

Ruby on Rails Heroku Error

I just tried to push my app to heroku but when I go to run heroku run rake db:migrate it says, "Cannot run one-off process at this time. Please try again later." ANy ideas as to what I can do?

Not able to execute rails test related commands

I am new to rails and trying to execute the test cases of an existing application but I am getting the below error.

[vagrant@localhost scams]$ RAILS_ENV=test rake db:migrate
rake aborted!
NoMethodError: undefined method `symbolize_keys' for nil:NilClass
/home/vagrant/myapp/scams/config/initializers/load_app_config.rb:2:in `<top (required)>'
/home/vagrant/.rvm/gems/ruby-2.1.0/gems/activesupport-4.2.7.1/lib/active_support/dependencies.rb:268:in `load'
/home/vagrant/.rvm/gems/ruby-2.1.0/gems/activesupport-4.2.7.1/lib/active_support/dependencies.rb:268:in `block in load'
/home/vagrant/.rvm/gems/ruby-2.1.0/gems/activesupport-4.2.7.1/lib/active_support/dependencies.rb:240:in `load_dependency'
/home/vagrant/.rvm/gems/ruby-2.1.0/gems/activesupport-4.2.7.1/lib/active_support/dependencies.rb:268:in `load'
/home/vagrant/.rvm/gems/ruby-2.1.0/gems/railties-4.2.7.1/lib/rails/engine.rb:652:in `block in load_config_initializer'
/home/vagrant/.rvm/gems/ruby-2.1.0/gems/activesupport-4.2.7.1/lib/active_support/notifications.rb:166:in `instrument'
/home/vagrant/.rvm/gems/ruby-2.1.0/gems/railties-4.2.7.1/lib/rails/engine.rb:651:in `load_config_initializer'
/home/vagrant/.rvm/gems/ruby-2.1.0/gems/railties-4.2.7.1/lib/rails/engine.rb:616:in `block (2 levels) in <class:Engine>'
/home/vagrant/.rvm/gems/ruby-2.1.0/gems/railties-4.2.7.1/lib/rails/engine.rb:615:in `each'

Someone please help to get rid of this error. I guess I am missing some steps.

(undefined method `year' for nil:NilClass) when saving date

I have a ruby on rails app. I added date_field to the view for add/Edit dates. the problem is that I have problem for saving and updating new dates but it brings the date from variable to the form(Edit) and after editting a date and creatine a new date. it doesn't come back to the home page or have problem with saving. as I saw in the console params, my date variable(start) changed when the user select new date but it does not load the first page afterward and I got this error:

    F, [2018-02-01T16:03:44.784113 #723] FATAL -- : 
NoMethodError (undefined method `year' for nil:NilClass):
  app/controllers/weeks_controller.rb:27:in `create'

here is my form page where it shows date to edit:

 .form-group
    = f.label :course
    = @course.name
  .form-group.form-inline
    = f.label :start
    = f.date_field :start, as: :date, value: f.object.try(:strftime,"%m/%d/%Y"), class: 'form-control'
    //= f.date_select :start, {}, { :class => "form-control" }
  .actions
    = f.submit 'Save', :class => "btn btn-primary"

an the error says about controller. but I do not have any 'year' method in controller:

 def create
     @week = Week.new(week_params.merge(course_id: @course.id))
     respond_to do |format|
     if @week.save
         format.html { redirect_to '/weeks', notice: 'was successfully created.' }
         format.json { render action: 'show', status: :created, location: @week }
       else
         format.html { render action: 'new' }
         format.json { render json: @week.errors, status: :unprocessable_entity }
       end
     end
  end



 def update
     respond_to do |format|
       if @week.update(week_params)
        format.html { redirect_to '/weeks', notice: 'starting week was successfully updated.' }
        format.json { head :no_content }
       else
         format.html { render action: 'edit' }
         format.json { render json: @week.errors, status: :unprocessable_entity }
       end
     end
   end

weeks_params defined as follows:

def week_params
      params.require(:week).permit(:start, :course_id)
    end

I have at first problem of showing date with date_select but now with date_field it shows that but I do not know where this error refers to. I would be thankful if any one would help me.