jeudi 30 mars 2017

Ruby: undefined method `delete'

I'm a newbie programmer, basically I'm trying to delete a record from a database table, however this record would be used on a child table with a composed primary key taking both from different tables.
This is the class of the table I need to delete the child data from.

class Detalle_Mapa 
  include DataMapper::Resource
  storage_names[:default] = 'detalle_ma'

  property :clave_mapa, String, :length => 2, :required => true, :key => true
  property :clave_asig, String, :length => 10, :required => true, :key => true
  property :clave_cuatri, String, :length => 2, :required => true

  belongs_to :mapa_curricular, 'Mapa_Curricular', :child_key => [:clave_mapa], :key => true
  belongs_to :cuatrimestre, 'Cuatrimestre', :child_key => [:clave_cuatri], :key => true
  belongs_to :asignatura, 'Asignatura', :child_key => [:clave_asig]

end

So now when I try to delete data from the parent table, it won't delete it since the PK is being used on the child table for other data. If this was normal SQL sintax it wouldn't be a big deal but I'm having a hard time finding a way around it on Ruby.

This is the basic method that works when deleting data that's not being used as a FK.

delete '/deleteMapCurricular/:clave_mapa' do
  @mapa = Mapa_Curricular.get(params[:clave_mapa])
  if @mapa      
     @mapa.destroy
     redirect '/catMapCurricular'
  end    
end

And this is one of the ways I've tried to delete the child data, which is clearly not right...

     Detalle_Mapa.where(:clave_mapa => [params[:clave_mapa]]).delete_all

Is there an easy way to just delete a bunch of data from a database that I'm not aware of? Or what I'm I not getting about this ActiveRecords on Ruby?

I'm sorry if the question is ambiguous or if I'm not explaining myself clearly, I usually find everything on forums and there is no need to ask myself. Any help will be greatly appreciated :)

503 (Service Unavailable: Back-end server is at capacity)

I have Amazone-E2 Server. My Rails application working on nginx and Unicorn. Suddenly I'm getting

503 (Service Unavailable: Back-end server is at capacity)

Unable to understand How to fix this issue. Kindly Help Please....

mercredi 29 mars 2017

Rails: Adding scope in a model using column values of same model in where clause

I am new to rails. I am trying to create a scope using where clause. In that where clause i want to use column values of same model. But i don't know the correct way of doing that. Please help me out. Here's the code snippet:

attr_accessible :booked_qty,
                :cancelled_qty,
                :quantity_shipped

This is the scope that i am trying to create:

scope :shipped_qty_less_than_max_tolerance_qty, where("quantity_shipped < ?",self.booked_qty-self.cancelled_qty)

So what's the best way to write this scope? Thanks in advance!

mardi 28 mars 2017

ActiveRecord::Enum - PG::InvalidTextRepresentation: ERROR: invalid input syntax for integer:

I am having a strange error and was hoping someone could point me in the right direction. I have a model called Organizations, and a attribute called department, see the excerpt from the schema below:

t.integer  "department",  default: 0

Inside my model have defined my enums for this attribute, as I am using ActiveRecord::Enum, like below:

enum department: [:conferences, :design_teams, :services, :clubs, :events, :communications]

But when I query, JobPosting.joins(job: :organization).where(organizations: { department: 'conferences' }) I get an error that reads:

PG::InvalidTextRepresentation: ERROR: invalid input syntax for integer: "conferences"

FYI: An Organization has_many Jobs, and Job has_many JobPostings.

But when I query Organization.where(department: 'conferences') it works.

Any help would be greatly appreciated.

Double Join Query Rails

I have three models, JobPosting, Job, and Organization. The relations are below:

  1. An Organization has many Jobs.
  2. A Job belongs to an Organization and has many JobPostings.
  3. A JobPosting belongs to a Job.

A Job has an attribute called job_type, and I am able to find all of the JobPostings that are related to a Job with a specific job_type using the query:

JobPosting.joins(:job).where(jobs: { :job_type => 'volunteer' })

But what I am struggling with is doing the same kind of thing but with an Organization attribute. A Organization has a attribute called department, how can I query for the JobPosting's that relate to an organization through a Job that has a specific department. The reason I am having trouble is because Organizations are essentially two levels up, whereas Job's are only one.

Any help would be greatly appreciated.

Refactor Similar Methods Redirects Different Rails

I wanted to get some advice on how I can refactor some code to make it more DRY, as Rails is very much about DRY. In my controller I have some methods like this:

def filter
  if params[:status] == "All" && params[:department] == "All"
    redirect_to admin_organizations_path
  elsif params[:status] != "All" && params[:department] == "All"
    redirect_to admin_organizations_path(status: params[:status])
  elsif params[:status] == "All" && params[:department] != "All"
    redirect_to admin_organizations_path(department: params[:department])
  else
    redirect_to admin_organizations_path(status: params[:status], department: params[:department])
  end
end

def filter_manage
  if params[:status] == "All" && params[:department] == "All"
    redirect_to manage_organizations_path
  elsif params[:status] != "All" && params[:department] == "All"
    redirect_to manage_organizations_path(status: params[:status])
  elsif params[:status] == "All" && params[:department] != "All"
    redirect_to manage_organizations_path(department: params[:department])
  else
    redirect_to manage_organizations_path(status: params[:status], department: params[:department])
  end
end

def filter_index
  if params[:department] == "All"
    redirect_to organizations_path
  else
    redirect_to organizations_path(department: params[:department])
  end
end

def filter_user
  if params[:department] == "All"
    redirect_to user_organizations_path
  else
    redirect_to user_organizations_path(department: params[:department])
  end
end

As you can see, the only real difference is where they are redirecting back to, how can make this a into a reusable piece of code that intelligently knows where to redirect back to given the view its coming from, because these methods are just redirecting back to the view they came from.

Any help is greatly appreciated!

lundi 27 mars 2017

Rails Javascript - refresh partial in view on click

In my project I am calling a partial in my view

game_player_main.html.erb:

<%= button_to "Wurfbild", home_player_statistic_detail_path(:game_id => @game.id, :player_id => @player.id, :home_or_away => @home_or_away, :player_mode => 'GoalArea'), class: 'btn_submit', :remote => true %>

player_statistic_detail.js.erb:

$("#player_statistic_detail").html("<%= escape_javascript render(partial: 'home/player_statistic_detail.html.erb', :handlers => [:erb]) %>");

Everything works fine. In my partial view I have a canvas field. By clicking this field it should reload the partial passing the x- and y-coordinates of the click event.

Here is my code:

_player_statistic_detail.html.erb:

<script>

var canvas = createHiDPICanvas(350, 228);
var ctx = canvas.getContext("2d");
canvas.addEventListener("mousedown", doMouseDown, false);

function doMouseDown(event) {
  canvas_x = event.pageX;
  canvas_y = event.pageY;

  canvas_x -= canvas.offsetLeft;
  canvas_y -= canvas.offsetTop;

  $("#player_statistic_detail").html("<%= escape_javascript render(partial: 'home/player_statistic_detail.html.erb', :handlers => [:erb]) %>");

}

If I just copy the javascript command into my view I am getting an error:

ActionView::Template::Error (stack level too deep)

Is it possible to refresh my partial player_statistic_detail.html.erb an d pass the coordinates?

dimanche 26 mars 2017

Rails nested layout routes

I have the base default layout application.html.erb which all the other pages are rendered into. Now I would like to do sort of the same thing for the users page.

Let s say I have /users/1/about which would be like the root page for the show method:

I have some sort of sidebar and by clicking on links I want some of the content to change. (about/interests/...)

For example the base layout for show would be:

application.html.erb > show.html.erb > about.html.erb

In show I would have something like:

<div class="col-xs-4">sidebar</div>
<div class="col-xs-8"> yield </div>

I assume that this would be somehow possible.

Rails get a has_one relation on a has_many relation

On a product/order and feedbacks relation how to find and relate the feedbacks to product?

Product Model
  has_many :orders
end

Order Model
  belongs_to :product
 belongs_to :feedback
end


Feedback Model
  has_one :order
end

I've tried get directly but how error someone have a hint?

Product Controller

def index
@total_feedbacks = Product.where(orders: Order.first).where('buyer_feedback_date is not null').count

@total_feedbacks = Feedback.joins(:products).where('products = ?', @products).where('buyer_feedback_date is not null').count

end
end

samedi 25 mars 2017

Rails files upload on production

I trying to upload an image on my local server with carrierwave there are no errors. But when i've tryed to upload same image on my production server i've validation errors (type of file, and empty field form). I also check rules, and in my public/uploads i've seted 777 What can it be?class ApplicationUploader < CarrierWave::Uploader::Base

include CarrierWave::MiniMagick

  storage :file

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

  def extension_white_list
    %w(jpg jpeg gif png)
  end

  def filename
    if original_filename
      @name ||= Digest::MD5.hexdigest(File.dirname(current_path))
      "#{@name}.#{file.extension}"
    end
  end

  def auto_orient
    manipulate!(&:auto_orient)
  end

  version :admin_thumb do
    process :auto_orient
    process resize_to_fit: [100, 100]
  end

  version :category_thumb do
    process :auto_orient
    process resize_to_fill: [327, 258]
  end

  version :list_thumb do
    process :auto_orient
    process resize_to_fill: [150, 115]
  end


end

my carrierwave uploader:

Override redirect on error in Devise registrations controller (Rails)

To add some custom logic to my sign up flow, I have overriden the default Devise registrations controller like this:

class RegistrationsController < Devise::RegistrationsController
  def new
    super
  end
end

# app/config/routes.rb
devise_for :users, :controllers => {:registrations => "registrations"}

The above is working fine. Now, I am trying to create different sign up views (which are maybe routed as /corporate/sign_up OR /personal/sign_up, whose forms all submit to my registrations controller.

But by calling super inside registrations controller, devise redirects to /users if there is any validation error (e.g. email already taken), which loads my original sign up view. How do I tweak this system to redirect to the custom sign up page which initiated the call to my registrations controller?

The only solution I could find is to copy all of the devise registrations controller logic here, and just return the error and not redirect.

What is a better solution for this?

rails deploy migrating run with root

When i do deploy, migrating run as root. i have error: Mysql2::Error: Access denied for user 'root'@'localhost' (using password: YES) But in my /shared/config/database.yml

default: &default
  adapter: mysql2
  pool: 5
  timeout: 5000
  database: sa

development:
  <<: *default
  user: root
  password: ""

test:
  <<: *default
  database: db/test.sqlite3

production:
  <<: *default
  user: sa
  password: "mypassss"

my capfile:

 require "capistrano/rvm"
 require "capistrano/bundler"
 require "capistrano/rails/migrations"
 require "capistrano/passenger"

Why migrating run as root but not as user sa?

vendredi 24 mars 2017

Providing an argument that looks like an option (rails runner / OptionParser / optparse)

I have a script magic which uses rails runner to invoke another script magic-foo.rb, which does it's own option parsing. Something like this:

exec("#rails", "runner", "#{some_path}/bin/magic-foo.rb", *arguments)

I want to expose the --help option from magic-foo.rb through magic, but rails runner consumes --help and dies with its own help message.

How can I get an argument that looks like an option through the use of OptionParser in runner.rb? Alternativel, how else can I get magic to evaluate magic-foo.rb in the right rails context with the right arguments?

Because an argument -- is the standard way to say "don't process following arguments" I might expect an invocation like this to work: rails runner .../magic-foo.rb -- [ARGS]. Unfortunately it does not.


Active version of rails runner: http://ift.tt/2nl0HH2 .

Rails: redirect_to(...) and return vs return redirect_to

When redirecting in rails 3,

Is return redirect_to(...) a valid Rails statement?

I've always just used redirect_to(...) and return but I saw a line like the one described above and I was surprised to see that it also worked.

jeudi 23 mars 2017

i want to find exclude a particular category from the foursquare api json how can i do it in ruby?

i want to find exclude a particular category from the foursquare api json how can i do it in ruby? in case i want to exclude Amphitheater and its sub categories?

"response": {
"categories": [
  {
    "id": "4d4b7104d754a06370d81259",
    "name": "Arts & Entertainment",
    "icon": {
      "prefix": "http://ift.tt/1ttca66",
      "suffix": ".png"
    },
    "categories": [
      {
        "id": "56aa371be4b08b9a8d5734db",
        "name": "Amphitheater",
        "categories": [{
            "id": "4bf58dd8d48988d134941735",
            "name": "Dance Studio",
            categories[sub categories #edited]
            ]
      }

mercredi 22 mars 2017

Rails how iterate has_one though?

This is the scenario:

so, the product did not have any relation with feedback, but the order has and i would like to show the feedbacks as belongs to products

model FEEDBACK

 has_one :order
 has_one :product, through: :order 

model ORDER

  belongs_to :product, touch: true
  belongs_to :feedback

model PRODUCT


  has_many :feedbacks
  has_many :orders

i'm would like to get the feedbacks of the product on a loop

for exemple

controller HOME


    @total_feedbacks = Feedback.joins(:product).where('products.id = ?', @product.id).where('buyer_feedback_date is not null').count


    @average_rating_from_buyers = Feedback.joins(:product).where('products.id = ?', @product.id).where('buyer_feedback_date is not null').rated(Feedback::FROM_BUYERS).average(:buyer_rating)






view HOME



  <table id="posts" class="product_table">
        <tbody class="page">
          <tr>
            <% @products.last(22).each do |product|%>

              <td>
                <%=link_to product_path(product.id), :class=>"product" do %>

                  <span class="productName">
                    <%=product.name %></span>
                  <span class="price"><%=number_to_currency(product.price, :unit=> "R$") %></span>


              <% if product.vitrine.feedbacks.present? %>
                    <div class="productFeeback">
                      <div><%= @average_rating_from_buyers %>"></div>
                      <%=@total_feedbacks %>
                    </div>
                  <% end %>

                <% end %>
              </td>
            <% end %>
          </tr>



        </tbody>
      </table>

with this code i'm getting

undefined method `id' for nil:NilClass

someone have a hint to spare? thank's

Overriding assign_attributes breaks Active:ModelForbiddenAttirbutesError exceptions and allows for mass attribute assignment

I have a module that was being used in a Rails 3 application to clean up bad characters from user form submissions. This worked fine under Rails 3 using attr_accessible in the models to prevent mass attr assignment, but with Strong Parameters in both Rails 3 and Rails 4 this is somehow bypassing Active:ModelForbiddenAttributesError exceptions so they never get raised and any params can be saved without first being permitted.

The module I'm using looks like this

module AttributeAssignmentCleaner
  def assign_attributes(new_attributes, opt= {})
    new_attributes = new_attributes.merge(opt)
    new_attributes = ris_attribute_cleaner(new_attributes)
    super(new_attributes)
  end

  def attributes=(new_attributes)
    new_attributes = ris_attribute_cleaner(new_attributes)
    super
  end

  def ris_attribute_cleaner(new_attributes)
    return new_attributes if new_attributes.nil?
    lookup = {
        "‘" => "'",
        "‛" => "'",
        "’" => "'",
        "“" => '"',
        "‟" => '"',
        "”" => '"',
        " " => '-',
        "‐" => '-',
        "‑" => '-',
        "‒" => '-',
        "–" => '-',
        "—" => '-',
        "―" => '-',
        "﹣" => '-',
        "-" => '-',
        "_" => '_',
        "︱" => '|',
        "︲" => '|',
        "•" => '*', }

    convert_char = Proc.new do |x|
      if lookup.has_key?(x)
        lookup[x]
      else
        ''
      end

    end
    new_attributes = new_attributes.inject({}) do |h, (key, val)|
      h[key] = case
                 when val == ''
                   nil
                 when val.is_a?(String) && val.ascii_only? == false

                   val = ActiveSupport::Multibyte::Chars.new(val).normalize(:kd).to_s
                   val = val.force_encoding("UTF-8").encode(
                       "us-ascii",
                       :fallback => convert_char
                   ).encode("UTF-8")

                 else
                   val
               end
      h
    end
  end
end

I would have expected this to work correctly as it calls super at the end; I would think the exceptions would get raised then, but this is not the case.

bootstrap modal placing overlay on entire screen and modal content not accessible

I am trying to open iframe in a bootstrap modal, but when the modal loads the overlay covers the entire screen including the popup and making it in accessible.

i have a div,

<div id="edit_batch" class="BatchGridPopup"></div>

the contents of this div are loaded via a ajax call, which loads the iframe.

when the iframe loads, i call the event $("#edit_batch").modal()

but this makes the overlay take up entire screen and i am unable to do any action on the popup or the screen.

Any help would be appreciated. Thanks.

Rails 3.2 Dynamic belongs to based off two separate columns

I have a model called TimesheetCorrection which has date column, a user_id column, hours column.

There is also a timesheet model which has the same columns. What I want to do is do a belongs_to :timesheet on the TimesheetCorrection model based on

WHERE timesheets.user_id = timesheet_corrections.user_id AND timesheets.date = timesheet_corrections.date

What would the syntax be to achieve that with active record?

Ruby on rails server not starting: bundler-1.14.6 `require': cannot load such file

Upgrading and old Ruby on rails app from ruby 1.9.3-p545 to ruby 2.3.1. on development server. Rails 3.2.8 will be upgraded to 4.2.8 (not done yet).

RVM and ruby version upgraded to 2.3.1, bundle installed successfully.

The following error occurs when running development server:

/home/javier/.rvm/gems/ruby-2.3.1/gems/activesupport-3.2.8/lib/active_support/values/time_zone.rb:270: warning: circular argument reference - now
/home/javier/.rvm/gems/ruby-2.3.1/gems/bundler-1.14.6/lib/bundler/runtime.rb:91:in `require': cannot load such file -- zip/zip (LoadError)
    from /home/javier/.rvm/gems/ruby-2.3.1/gems/bundler-1.14.6/lib/bundler/runtime.rb:91:in `block (2 levels) in require'
    from /home/javier/.rvm/gems/ruby-2.3.1/gems/bundler-1.14.6/lib/bundler/runtime.rb:86:in `each'
    from /home/javier/.rvm/gems/ruby-2.3.1/gems/bundler-1.14.6/lib/bundler/runtime.rb:86:in `block in require'
    from /home/javier/.rvm/gems/ruby-2.3.1/gems/bundler-1.14.6/lib/bundler/runtime.rb:75:in `each'
    from /home/javier/.rvm/gems/ruby-2.3.1/gems/bundler-1.14.6/lib/bundler/runtime.rb:75:in `require'
    from /home/javier/.rvm/gems/ruby-2.3.1/gems/bundler-1.14.6/lib/bundler.rb:107:in `require'
    from /home/javier/Workspace/e-nrg/config/application.rb:7:in `<top (required)>'
    from /home/javier/.rvm/gems/ruby-2.3.1/gems/railties-3.2.8/lib/rails/commands.rb:53:in `require'
    from /home/javier/.rvm/gems/ruby-2.3.1/gems/railties-3.2.8/lib/rails/commands.rb:53:in `block in <top (required)>'
    from /home/javier/.rvm/gems/ruby-2.3.1/gems/railties-3.2.8/lib/rails/commands.rb:50:in `tap'
    from /home/javier/.rvm/gems/ruby-2.3.1/gems/railties-3.2.8/lib/rails/commands.rb:50:in `<top (required)>'
    from script/rails:6:in `require'
    from script/rails:6:in `<main>'

How to draw polyline on google map in rails?

I am drawing polyline with marker on Google map using js. I want to draw this image enter image description here

How to implement it ?

Rails server does not start due to the error I got last time

I'm using rails on vagrant to create an application. In the app, I was playing around with open-uri, and it did not work so I stopped the server. Then, I keep getting the following error when I try to run my server or even rails console. /rbenv/versions/2.2.2/lib/ruby/2.2.0/open-uri.rb:358:in `open_http': 503 Service Unavailable (OpenURI::HTTPError)

My guess is that some old files exist and they are causing the errors, but I'm not sure what to do.

I'd appreciate it if someone could help me out.

Thanks.

lundi 20 mars 2017

Rails_admin model feature that is a function of other features

I am currently using the rails_admin gem for a project,to create back office for a database and I want to update one of my models. The issue is the new attribute is a function of one of the other attributes and isn't an entry in the database. IE the model has a feature my_id and I want to add a feature dif_id which is a function of my_id.

Any ideas how to do this?

How to execute query over Amazon Athena with ruby?

how to connect Amazon Athena with Ruby and execute query over Amazon Athena and get result.

we not able to find any gem or example with help us to connect Amazon Athena in ruby.

Please provide any refrance using which we can use to build connection with Amazon Athena and build custom query exector in ruby.

dimanche 19 mars 2017

Error message: First argument in form cannot contain nil or be empty

I have aproblem with my Rails application. I'm getting the following error message for my project.start.html.erb: First argument in form can not contain nil or be empty ...

What can be the reason?

Here are my related files:

project.start:

<div class="row">
  <div class="span5">
    <h2>Programme</h2>
    <%= form_for (@project) do |f| %>
        <div class="field">
          <%= f.label :path, "GAMS-Verzeichnis" %>
          <%= f.text_field :path %>
          <a href="http://ift.tt/J755SN">(GAMS-Download)</a>
        </div>

        <br/>

        <div class="actions">
          <%= f.submit 'Verzeichnisse aktualisieren', :class => "btn"  %>
        </div>
    <% end %>
  </div>
</div>

projects.controller:

class ProjectsController < ApplicationController
  before_action :set_project, only: [:show, :edit, :update, :destroy]

  # GET /projects
  # GET /projects.json
  def index
    @projects = Project.all
  end

  # GET /projects/1
  # GET /projects/1.json
  def show
  end

  # GET /projects/new
  def new
    @project = Project.new
  end

  # GET /projects/1/edit
  def edit
  end

  # POST /projects
  # POST /projects.json
  def create
    @project = Project.new(project_params)

    respond_to do |format|
      if @project.save
        format.html { redirect_to @project }
        format.json { render :show, status: :created, location: @project }
      else
        format.html { render :new }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

  # PATCH/PUT /projects/1
  # PATCH/PUT /projects/1.json
  def update
    respond_to do |format|
      if @project.update(project_params)
        format.html { redirect_to @project }
        format.json { render :show, status: :ok, location: @project }
      else
        format.html { render :edit }
        format.json { render json: @project.errors, status: :unprocessable_entity }
      end
    end
  end

  # DELETE /projects/1
  # DELETE /projects/1.json
  def destroy
    @project.destroy
    respond_to do |format|
      format.html { redirect_to projects_url }
      format.json { head :no_content }
    end
  end

  private
    # Use callbacks to share common setup or constraints between actions.
    def set_project
      @project = Project.find(params[:id])
    end

    # Never trust parameters from the scary internet, only allow the white list through.
    def project_params
      params.require(:project).permit(:name, :deadline, :closed, :gvp, :path, :startdate, :zwt, :zwc, :totalc, :extrac)
    end
end

Tanks for the help! :)

How should I track user activity for different tasks user has performed

I am trying to record user's activity that user performs. User is associated with 3 models for which I am trying to track his activity.

class User < ActiveRecord::Base
  has_many :tasks, :dependent => :destroy
  has_many :comments, :dependent => :destroy
  has_many :rating, :dependent => :destroy
end



class Task < ActiveRecord::Base
   belongs_to :user
end
class Rating < ActiveRecord::Base
   belongs_to :user
end
class Comment < ActiveRecord::Base
   belongs_to :user
end

  1. Task model entry is created whenever user is assiged for a task.
  2. Rating entry is created when other user gives a rating to that user.
  3. Comment entry is created when some user comments on his task.

Now I want to list these activities of these 3 models for that user according to recency.

Should I create another table named as user_activity table and every time create a record in user_activity that table whenever any record is created in above three models. Or should I take use of above three models and search from these tables for user activity on the fly whenever user activity API is called.

What should be the best approach?

Adding Categories In Rails 3

I am building an uploader for videos and giving the videos a category through categorizations. Every time I try to upload a video I receive an error saying

NameError in VideosController#create

uninitialized constant Video::Categorization

I want to able to add one category to each video. But no regardless of how I write the association I get the same error.

model

 class Video < ActiveRecord::Base

  attr_accessible :source, :title, :url, :description,
                :category, :category_id, :category_list

 belongs_to :user

 has_many :category, through: :categorizations
 has_many :categorizations
 validates :category, presence: true

 has_attached_file :source

  def source_remote_url=(url_value)
   self.source = URI.parse(url_value) unless url_value.blank?
   super
  end

  def self.categorized_with(name)
    Category.find_by_name!(name).videos
  end

  def category_list
    ["Action",  "Anime",
      "Arts and Culture",  "Beauty",  "Business", "Comedy", 
      "Documentary", "Drama", 
      "Food",  "Gaming",  "Health and Fitness",  "Horror"]
  end 

  def category_list=(names)
    self.category = names.split(",").map do |n|
     Category.where(name: n.strip).first_or_create!
    end
  end

end

Video Controller

class VideosController < ApplicationController
  before_filter :authenticate_user!
  before_filter :set_video, only: [:show, :edit, :update, :destroy]

  respond_to :html

 def index
   @videos = Video.all
 end

 def show
  respond_with(@video)
 end

 def new
   @video = Video.new
   respond_with(@video)
 end

 def edit
 end

 def create
   @video = Video.new(params[:video])
   @video.save
   respond_with(@video)
 end

def update
  @video.update_attributes(params[:video])
  respond_with(@video)
end

 def destroy
  @video.destroy
  respond_with(@video)
 end

 private
   def set_video
     @video = Video.find(params[:id])
   end
end

Form

<%= form_for(@video) do |f| %>
  <% if @video.errors.any? %>
    <div id="error_explanation">
      <h2><%= pluralize(@video.errors.count, "error") %> prohibited this video from being saved:</h2>

      <ul>
      <% @video.errors.full_messages.each do |msg| %>
        <li><%= msg %></li>
      <% end %>
      </ul>
    </div>
  <% end %>

  <div class="field">
    <%= f.label :title %><br />
    <%= f.text_field :title %>
  </div>

  <div class="field">
    <%= f.label :source %><br />
      <%= f.file_field :source %>
  </div>

    <div class="field">
      <%= f.label "Category", class: 'control-label' %>
      <%#= f.select :category, Category.all, :prompt => 'Select One' %>
    <%= f.select :category_list, video_category, :prompt => "Select a category..." %>

    </div>

  <div class="field">
    <%= f.label :description %><br />
   <%= f.text_area :description, rows: 4, placeholder: "Description" %>

</div>
<div class="actions">
    <%= f.submit %>
  </div>
<% end %>

Error when trying to making dynamic error page in rails application

I've created rails app and I've made dynamic error 404/500 page through ErrorsController:

class ErrorsController < ApplicationController
  def not_found
    render status: 404
  end

  def internal_server_error
    render status: 500
  end
end

and changing routes.rb to this:

Rails.application.routes.draw do
  resources :books
  root 'welcome#index'
  match "/404", :to => "errors#not_found", :via => :all
  match "/500", :to => "errors#internal_server_error", :via => :all
end

but whenever I run app this error comes:

Error during failsafe response: Missing template errors/200 with {:locale=>[:en], :formats=>[:css], :variants=>[], :handlers=>[:raw, :erb, :html, :builder, :ruby, :coffee, :jbuilder]}. 

and I just enable to see internal_server_error.html.erb in browser.
How can solve this?

using attr_accessor for validation always returns an error

I'm trying to validate 2 fields which do no belong to the User table

attr_accessor :terms_of_service, :privacy_policy

 validates :terms_of_service, presence: true
 validates :privacy_policy, presence: true

in the request sent from the client, the :terms_of_service and :privacy_policy arguments can either be absent, or a boolean value.

Rails needs to pass validation only if the value is true (i.e send error only if parameter is absent or false)

however , for some reason - validation always fails regardless of the parameters being true or absent/false

I've even tried

 validates_presence_of :terms_of_service
 validates_presence_of :privacy_policy

and also

  validates :terms_of_service, acceptance: true
  validates :privacy_policy, acceptance: true

Rails model validation - undefined method error

i'm trying to validate the presence on a parameter in rails. this is the code snippet for User.rb

  validates :terms_of_service, presence: true 
  validates :privacy_policy, presence: true

Ideally , i would like rails to throw an error if this parameter is not present

here is a sample parameter list sent by the client

Parameters: {"username"=>"f", "email"=>"f@f.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "confirm_success_url"=>"http://localhost:4000", "config_name"=>"default", "registration"=>{"username"=>"f", "email"=>"f@f.com", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]", "confirm_success_url"=>"http://localhost:4000"}}

However, rails throws the below error

NoMethodError (undefined method `terms_of_service' for #<User:0x007f16d402e788>):

why does it think that there should be a terms_of_service method when i'm actually testing a parameter?

Rails find object id on has_many association

I'm trying to get the transaction id associated with the current_user but rails shos this error below

error:

ActiveRecord::RecordNotFound (Couldn't find Transaction with id=92 [WHERE "transactions"."user_id" = 24])

iv'e tried use where and just the transaction and with a conditional comparing the transaction.user_id with the current_user.id but show error!

someone have any hint about this kind of issue?

model user

user has_many transactions

model transaction 

transaction belongs to user


transaction controller

def new
@transaction = Transaction.new
end

def create

@transaction = Transaction.build_user

end



def show

@transaction = current_user.transactions.find(params[:id])

end

samedi 18 mars 2017

rails check if url ends with number

I am trying to create a redirect_to :back that is triggered after a person object is deleted. There are several pages a user can come from before triggering the delete object code. If they come from the person#show page, i want to redirect to a route called admin_persons_path. If they come from any other page, I just want the user to be redirected back to the page they are on. The persons#show page has a url structure of localhost:3000/admin/persons/[some_id_number] . I am trying to write code that reads the referrer url and redirects accordingly. I am trying to do something like:

if request.referer.end_with?(some regular expression)
    redirect_to :back
else
    redirect_to admin_persons_path
end

The problem is that I dont think the end_with? method can accept a regular expression because when I try it with a regex i get the error:

TypeError: no implicit conversion of Regexp into String

How do I get this to work?

Please note using redirect_back(fallback_location: admin_persons_path) won't work because the referrer technically exists. If there is a built-in method that accomplishes what I want, I am unaware of it.

Twitter-Like "Reply and Retweet" Rails 3

I'm building a sample rails application that mimics some of my favorite apps. I want to implement a photo reply to a photo and a repost of a photo -- Similar to the way you reply and retweet via Twitter. Should I make a separate relationship model that captures the photo replies and reposts or should I handle everything in the photo model.

class Photo < ActiveRecord::Base

   attr_accessible :caption, :source, :source_remote_url, :source_file_name, 

   has_attached_file :source
   validates_attachment_content_type :source 

   belongs_to :user

   has_many :replies
   has_many :reposts  

  def source_remote_url=(url_value)
    self.source = URI.parse(url_value) unless url_value.blank?
   super
  end

 def replies
   join_table 
 end

 def replies?(other_user)
   join_table.find_by_replied_id(other_user.id)
 end

 def reply!(other_user)
   join_table.create!(replied_id: other_user.id)
 end

vendredi 17 mars 2017

Redirect to page with form fields filled

I have to models in my application:

class User < ActiveRecord::Base
  has_many :telephones
end

class Telephone < ActiveRecord::Base
  belongs_to :user
end

and in my form to user i have user's fields and link to new or edit telephones, something like this:

.panel.panel-default
  .panel-heading User
  .panel-body
    .row
      = f.input :name, wrapper_html: { class: "col-md-8" }
      = f.input :age, wrapper_html: { class: "col-md-4" }
    .row
      .col-md-4
        h4 Telefones
        - unless user.telephones.blank?
          table.table.table-borded
            thead
              tr
                th= Telephone.human_attribute_name(:title)
                th= Telephone.human_attribute_name(:number)
                th

            tbody
              - user.telephones.each do |telephone|
                tr
                  td= telephone.title
                  td= telephone.number
                td
                  = link_to(fa_icon("edit"), edit_telephone_path(telephone), class: "btn btn-sm btn-default") + " "
                  = link_to fa_icon("trash-o"), telephone_path(telephone), class: "btn btn-sm btn-danger",
                                                                              method: :delete,
                                                                              data: { confirm: t("titles.confirm") }
         = link_to(fa_icon("plus", text: "New"), new_telephone_path(), class: "btn btn-sm btn-success")

If I fill in the username and age field of the user and click in button New, my application redirect to Telephone form, and after create, redirect back to User form with telephone created, but the data of fields name and age are lost. Why i do this saving user data when click in button New and redirect user form filled after create telephone??

How to run system command on heroku server?

I am using OGR2OGR for converting geojson file into dxf format. It is working on local server but on heroku server it is not working. Find code which is using for genrating file:

  • str2 = {"type":"FeatureCollection", "features":[ {"type":"Feature","properties":{"color":"red"},"geometry":{"type":"Point","coordinates":[@substation]}}, {"type":"Feature","properties":{"color":"red"},"geometry":{"type":"Point","coordinates":[@feeder]}}, {"type":"Feature","properties":{"color":"red"},"geometry":{"type":"Point","coordinates":[@form3]}}, {"type":"Feature","properties":{"color":"red"},"geometry":{"type":"Point","coordinates":[@pdt_array]}}, {"type":"Feature","properties":{"color":"red"},"geometry":{"type":"Point","coordinates":[@edt_array]}}, {"type":"Feature","properties":{"color":"red"},"geometry":{"type":"Point","coordinates":[@composite_array]}}, {"type":"Feature","properties":{"color":"red"},"geometry":{"type":"Point","coordinates":[@al_array]}}, {"type":"Feature","properties":{"color":"red"},"geometry":{"type":"Point","coordinates":[@tp_array]}}, {"type":"Feature","properties":{"color":"red"},"geometry":{"type":"Point","coordinates":[@ot_array]}},

     {"type":"Feature","properties":{"color":"red"},"geometry":{"type":"LineString","coordinates":[@lt_array,@ht_array,@consumer_array]}}
    
    

    ]} path = "#{Rails.root}/public/data.geojson" File.open(path, "w+") do |f| f.write(JSON.pretty_generate(str2)) end system("ogr2ogr -f DXF #{Rails.root}/public/delhiii.dxf #{Rails.root}/public/data.geojson")

rails s says "brunch_watcher.rb:1:in `require': cannot load such file -- pty (LoadError)" in RailsInstaller

I installed breakfast in my rails project on Windows 10 PC. When I run rails s and it throw exception

D:/Development/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/breakfast-0.5.1/lib/breakfast/brunch_watcher.rb:1:in `require': cannot load such file -- pty (LoadError)
    from D:/Development/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/breakfast-0.5.1/lib/breakfast/brunch_watcher.rb:1:in `<top (required)>'
    from D:/Development/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/breakfast-0.5.1/lib/breakfast.rb:3:in `require'
    from D:/Development/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/breakfast-0.5.1/lib/breakfast.rb:3:in `<top (required)>'
    from D:/Development/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/bundler-1.13.7/lib/bundler/runtime.rb:91:in `require'
    from D:/Development/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/bundler-1.13.7/lib/bundler/runtime.rb:91:in `block (2 levels) in require'
    from D:/Development/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/bundler-1.13.7/lib/bundler/runtime.rb:86:in `each'
    from D:/Development/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/bundler-1.13.7/lib/bundler/runtime.rb:86:in `block in require'
    from D:/Development/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/bundler-1.13.7/lib/bundler/runtime.rb:75:in `each'
    from D:/Development/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/bundler-1.13.7/lib/bundler/runtime.rb:75:in `require'
    from D:/Development/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/bundler-1.13.7/lib/bundler.rb:106:in `require'
    from D:/ProjectExt/confess_server/config/application.rb:7:in `<top (required)>'
    from D:/Development/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.2/lib/rails/commands/commands_tasks.rb:88:in `require'
    from D:/Development/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.2/lib/rails/commands/commands_tasks.rb:88:in `block in server'
    from D:/Development/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.2/lib/rails/commands/commands_tasks.rb:85:in `tap'
    from D:/Development/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.2/lib/rails/commands/commands_tasks.rb:85:in `server'
    from D:/Development/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.2/lib/rails/commands/commands_tasks.rb:49:in `run_command!'
    from D:/Development/RailsInstaller/Ruby2.3.0/lib/ruby/gems/2.3.0/gems/railties-5.0.2/lib/rails/commands.rb:18:in `<top (required)>'
    from bin/rails:9:in `require'

jeudi 16 mars 2017

Select all files in all directories ending with specific names in ruby

I have a lot of csv files which are saved in multiple directories. I would like to select names which ends with specific name such as "DWA日本語の名前).csv". Note that the name contains both english and Japanese characters and I do not know if this is the right way to select files ending with specific string.

path => "/mnt/resource2/sgsystem/20160206-4/**/*\"DWA日本語の名前).csv"

This is part of input plugin to export data to elasticsearch. It does not throw an error, but the data are not exported to elasticsearch. However, when I replace the Japanese characters (日本語の名前) with English characters(e.g., DWAjapanese.csv), it works properly. Any clue what is wrong here.

How to run rails commands in production with capistrano 3 and rvm installed

I'm struggling to get a decent understanding of capistrano. I want to run rails commands in production but it seems that the corresponding binstub is nowhere to be found. As a matter of fact, I have the current/ and shared/ directories under my app name, but none of both has a bin/ directory with a rails binstub.

I'm also a complete newbie at building capistrano tasks. I found out this gem for example to run rails c with capistrano, but it requires the rails binstub in the current/bin directory, which of course I don't have.

For your reference, here's my config/deploy.rb:

set :scm,             :git
set :repo_url,        '<git_repo>'
set :application,     '<app_name>'
set :user,            '<production_user>'
set :puma_threads,    [4, 16]
set :puma_workers,    0
set :pty,             true
set :use_sudo,        false
set :stage,           :production
set :deploy_via,      :remote_cache
set :deploy_to,       "/home/#{fetch(:user)}/#{fetch(:application)}"
set :puma_bind,       "http://unix#{shared_path}/tmp/sockets/#{fetch(:application)}-puma.sock"
set :puma_state,      "#{shared_path}/tmp/pids/puma.state"
set :puma_pid,        "#{shared_path}/tmp/pids/puma.pid"
set :puma_access_log, "#{release_path}/log/puma.error.log"
set :puma_error_log,  "#{release_path}/log/puma.access.log"
set :ssh_options,     { forward_agent: true, user: fetch(:user), keys: %w(~/.ssh/id_rsa.pub) }
set :puma_preload_app, true
set :puma_worker_timeout, nil
set :puma_init_active_record, true  # Change to false when not using ActiveRecord

## Defaults:
# set :branch,        :master
# set :format,        :pretty
# set :log_level,     :debug
# set :keep_releases, 5

## Linked Files & Directories (Default None):
set :linked_files, %w{config/application.yml config/database.yml config/secrets.yml}
set :linked_dirs,  %w{bin log tmp/pids tmp/cache tmp/sockets vendor/bundle public/system public/uploads}

# Bonus! Colors are pretty!
def red(str)
  "\e[31m#{str}\e[0m"
end

# Figure out the name of the current local branch
def current_git_branch
  branch = `git symbolic-ref HEAD 2> /dev/null`.strip.gsub(/^refs\/heads\//, '')
  puts "Deploying branch #{red branch}"
  branch
end

# Set the deploy branch to the current branch
set :branch, current_git_branch

namespace :puma do
  desc 'Create Directories for Puma Pids and Socket'
  task :make_dirs do
    on roles(:app) do
      execute "mkdir #{shared_path}/tmp/sockets -p"
      execute "mkdir #{shared_path}/tmp/pids -p"
    end
  end

  before :start, :make_dirs
end

namespace :assets do
  desc "compile assets locally and upload before finalize_update"
  task :deploy do
      %x[bundle exec rake assets:clean && bundle exec rake assets:precompile]
      ENV['COMMAND'] = " mkdir '#{release_path}/public/assets'"
      invoke
      upload '/#{app_dir}/public/assets', "#{release_path}/public/assets", {:recursive => true}
  end
end

namespace :deploy do
  desc "Make sure local git is in sync with remote."
  task :check_revision do
    on roles(:app) do
      #unless `git rev-parse HEAD` == `git rev-parse origin/master`
      #  puts "WARNING: HEAD is not the same as origin/master"
      #  puts "Run `git push` to sync changes."
      #  exit
      #end
    end
  end

  desc 'Initial Deploy'
  task :initial do
    on roles(:app) do
      before 'deploy:restart', 'puma:start'
      invoke 'deploy'
    end
  end

  task :fix_absent_manifest_bug do
    on roles(:web) do
      within release_path do  execute :touch,
        release_path.join('public', fetch(:assets_prefix), 'manifest-fix.temp')
      end
   end
  end


  # desc 'Restart application'
  # task :restart do
  #   on roles(:app), in: :sequence, wait: 5 do
  #     invoke 'puma:restart'
  #   end
  # end

  before :starting,     :check_revision
  after  :finishing,    :compile_assets
  after  :finishing,    :cleanup
  after  :finishing,    :restart
  after  :updating, 'deploy:fix_absent_manifest_bug'
end

# ps aux | grep puma    # Get puma pid
# kill -s SIGUSR2 pid   # Restart puma
# kill -s SIGTERM pid   # Stop puma

and my Capfile:

# Load DSL and set up stages
require 'capistrano/setup'

# Include default deployment tasks
require 'capistrano/deploy'

# Include tasks from other gems included in your Gemfile
#
# For documentation on these, see for example:
#
#   http://ift.tt/PSLPeH
#   http://ift.tt/1nFai6c
#   http://ift.tt/1nFai6d
#   http://ift.tt/1nFai6f
#   http://ift.tt/1nFai6g
#   http://ift.tt/1z5Iifp
#
# require 'capistrano/rvm'
# require 'capistrano/rbenv'
# require 'capistrano/chruby'
# require 'capistrano/bundler'
# require 'capistrano/rails/assets'
# require 'capistrano/rails/migrations'
# require 'capistrano/passenger'

require 'capistrano/setup'
require 'capistrano/deploy'

require 'capistrano/rails'
require 'capistrano/bundler'
require 'capistrano/rvm'
require 'capistrano/puma'

require 'capistrano/rails/collection'

# Load custom tasks from `lib/capistrano/tasks` if you have any defined
Dir.glob('lib/capistrano/tasks/*.rake').each { |r| import r }

Am I missing something? Thanks in advance

Rails 3 switching to strong parameters ForbiddenAttributesProtection error not raised?

I'm attempting to add strong parameters to a Rails 3 application, but it is still permitting all mass attribute assignment and doesn't raise an error for ForbiddenAttributesProtection.

I have created an initializer strong_parameters.rb that has the following

ActiveRecord::Base.send(:include, ActiveModel::ForbiddenAttributesProtection)

Additionally I have commented out config.active_record.whitelist_attributes = true in my config/application.rb file and removed all instances of attr_accessible from my models.

I also added the following to my config/application.rb so that I would get an exception in all environments until I'm done testing out the cutover.

config.action_controller.action_on_unpermitted_parameters = :raise

Despite these changes I can submit any of my existing forms and updates are saved without any exceptions being raised.

How to genrate GeoJson file in rails?

I am trying to generate file in .geojson in rails rails with dynamic coordinates(fetch coordinated from DATABASE). How i can achieved in ruby on rails ? It is throughout error : Unable to open datasource '/public/data.geojson' with the following drivers.

Replace until all occurences are removed

I have the following strings:

",||||||||||||||"
",|||||a|||||,|"

I would like to achieve that all occurrences of ",|" are replaced with ",,"

The output should be the following:

",,,,,,,,,,,,,,,"
",,,,,,a|||||,,"

When I run .gsub(',|', ',,') on the strings I get not the desired output.

",,|||||||||||||"
",,||||a|||||,,"

That's because it does not run gsub several times. Is there a similar method that runs recursively.

Adding differential update feature in ruby app

I am making a Ruby mobile app on Rhomobile. I am looking to have differential update feature in it. i.e Every time when a user installs the app, all files and folders are not installed but the new files added, existing modified or deleted are updated. How can i do it.

mercredi 15 mars 2017

RoR - Devise and scaffolding errors

I created a user authentication using Devise and a scaffolding to do a CRUD. The problem is: When I create a new user, the same can be the datas stored from other users. All users can see the datas from all users. I wanna that each user has your clients, products or whatever is in the scaffolding folders that I have created.

how to send email in rails with socks (4, 4.5 and 5)

I want to send mail in rails with socks, but i can't find docs about send mail with config socks. http://ift.tt/1gKQ1tC

Anyone can give me a keyword or document. tks.

I was hoping for some help debugging this ruby script. I'm having trouble using the output function from outside the class

I'm having an issue with calling the method output statically from outside of the class. I get this error: undefined method output' for #<WeightedScore:0x007ffb3815d840> (repl):58:in' (repl):9:in `'

My Code: Ruby Script

Thank you for the help!

Accessing rails loop variable in JQuery

I have the following html code:

.panel
.row
  .columns.small-6.medium-4
    = city_business_units_select_tag @appointment
  .columns.small-6.medium-4
    = select_tag 'appointment[asset_id]', options_for_select(current_cbu.assets.collect{|asset| [ asset.name, asset.id ] }, @appointment.asset_id), include_blank: true

.row
  .columns.small-6.medium-4
    =f.label :technician_id
    =f.select :technician_id, Technician.order(:last_name, :first_name).map {|t| [t.full_name, t.id]}, {selected: @technician_id, prompt: 'Select Technician', include_blank: true}

So basically when the city_business_units_select_tag is changed, i want to hide certain elements on the technician select using jquery. How do I get the variable "technician" for each option object as I loop over it?

    $("#appointment_city_business_unit_id").change(function(){
       $("#appointment_technician_id > option").each(function () {
          console.log(technician.city_buiness_unit);
       });
    });

Rails add new and edit form in bootstrap modal

I'm new with Runy on Rails. Now I'm trying to make a simple ToDo List app with bootstrap. Everything works but I tryed to render my New task form to modal window and it's crashed. Here is my _form partial code:

  <div id="myModal" class="modal fade" role="dialog">
    <div class="modal-dialog">
      <!-- Modal content-->
      <div class="modal-content">
        <div class="modal-header">
          <button type="button" class="close" data-dismiss="modal">&times;</button>
          <h4 class="modal-title">Modal Header</h4>
        </div>      
      </div>
        <div class="modal-body">
          <h1>New Task</h1>
          <%= form_for @task, :html => {class:"form-horizontal"} do |f|%>
             <!-- Here is form code -->
          <% end %>
          <%= link_to 'Back', tasks_path %>
        </div>
        <div class="modal-footer">
          <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
        </div>
      </div>
    </div>

And here is my Index.html.erb:

<div class="container-fluid">
    <div class="row">
        <h1 class="text-left">Task List</h1>
        <%= button_to 'New Task', new_task_path, :class =>"btn btn-success pull-right", :method => "get", data: {'data-toggle' => "modal", 'data-targe' => "#myModal"} %>
    </div>
    <div class="row button-margin ">
    <% @tasks.each do |task| %>
            <div class="panel <%= task_status(task) %>">
                <div class="panel-heading">
                    <%= task.title %>
                    <p class="pull-right"><%= task.dueDate %></p>
                </div>
                <div class="panel-body">    
                    <h3><%= task.body %></h3>
                </div>
            </div>
        <% end %>
    </div>

    <%= render "tasks/form" %>
</div>

So when trying to start my index page I get an error "First argument in form cannot contain nil or be empty". Whats wrong with my code? And how can I pass an exsisting task to form for Edit action?

mardi 14 mars 2017

Override gem method in rails

I want to let users add interests -TV shows in this case-, and to make sure they type a correct tv show, I'm going to search imdb first and let them select one of the returning titles.

I found this gem http://ift.tt/2eeGrRY which is doing almost what I need. If I search for "The vampire diaries", it will return it and 200 extra matches.

I went through the gem and I found that he does the querying part here http://ift.tt/2n7yu7p.

   def self.query(query)
      open("http://ift.tt/2nC3c51")
   end

That query basically uses this link http://ift.tt/2n7oQ4D and returns everything that can find given the input - movies, tv shows, episodes. Now I found a more advanced query which uses type and some other params. So I could actually return only 4 results in that case instead of 250. All I have to do is to replace that query with http://ift.tt/2nC8U7d.

How do I override that search method?

Rails running on bash on ubuntu

I am trying to make a setup for developing Ruby On Rails from Bash On ububntu but with a mysal db running on docker. Mysql is running fine and i connect to it with

docker exec -it myinstance mysql -uroot -p

I got my rails app running after running bundle install and then rails s. But when I hit the page or try executing rake db:migrate i get an error

Lost connection to MySQL server at 'reading initial communication packet', system error: 0

Maybe it is my MySql setup on bash that is not ok? Or maybe there is some limit to bash here? Any help is much appreciated.

I tried connecting from bash with mysql command but no luck either

Anyone has tried something similar?

SQL + Rails - How to query the same column in 2 tables in hierarchy, when the child's value is NULL in the database?

class Baby
  belongs_to :child
  attr :is_public
  scope :public, includes(:child).merge(Child.public).where('babies.is_public IS TRUE')
end

class Child
  belongs_to :parent
  attr :is_public

  scope: public, where ???
  def is_public; read_attribute(:is_public).blank? ? self.parent.is_public : super(); end
end

class Parent
  has_many :children
  attr :is_public
end

situation: child.is_public is NULL in the database and the parent.is_public is true in the database

Issues:

  1. Child.public should give the correct result based on inheritance
  2. same column query - .merge(Child.public)

Issue 1: I think it would work with an sql if statement or case statement, so I already tried some things but no luck yet:

Child.includes(:parent).select("CASE WHEN children.is_public IS NOT NULL AND children.is_public IS TRUE THEN TRUE WHEN children.is_public IS NULL AND parent.is_public IS TRUE THEN TRUE END")

I think I am not the sql IF and CASE statements the way they were intended, I am still looking for the answer, but your help would be very much appreciated :)

rails assets in production not served (yet another assets issue)

I'm using apache 2.2.15 passenger 5.1.2 rails 4.2.6 ruby 2.3.3

In the rails log, I get

(No route matches [GET] application-xxxxx.js

as well as

(No route matches [GET] application-xxxxx.css

I can find the assets in the public/assets directory.

My manifests:

app/assets/stylesheets/application.css.less:

/*
 *= require jquery-ui
 *= require font-awesome
 *= require bootstrap_and_overrides
 *= require awesome-bootstrap-checkbox
 *= require lists
 *= require mailgroups
 *= require general
 *= require colors
 *= require print
 *= require loader
 *= require tooltips
 *= require_self
 *= require_tree .
*/

app/assets/javascripts/application.js

//= require jquery
//= require jquery.turbolinks
//= require jquery_ujs
//= require jquery-ui
//= require twitter/bootstrap
//= require bootstrap
//= require turbolinks
//= require twitter/bootstrap/rails/confirm
//= require_self
//= require_tree .

and I set (following other answers here on SO) in config/production.rb

config.serve_static_files = true

in app/views/layouts/application.html.erb

<%= stylesheet_link_tag "application", media: "all", "data-turbolinks-track" => "reload" %>
<%= javascript_include_tag "application", "data-turbolinks-track" => "reload" %>

I'm lost, thanks for your help.

API hit error in ror gives - Completed 500 Internal Server Error , TypeError (no implicit conversion of nil into String)

My routes.rb -

Rails.application.routes.draw do
  root 'welcome#index'

  namespace :api, defaults: { format: :json } do
namespace :v1 do
  get "/users/:cv_id" => "engine#users_get"
  post "/users" => "engine#users_add"
end
end

and my main controller is --

   class Api::V1::MainController < ApplicationController

 http_basic_authenticate_with name: ENV["API_USERNAME"], password: ENV["API_PASSWORD"]


 API_CMDS_LIST = {
"Engine"  => [:users_add, :users_update],
}

 include Api::V1::ErrorMessage
  skip_before_filter :verify_authenticity_token
  protect_from_forgery with: :null_session

  def resulting_json(resp)
    if resp[:result] == "error" && !resp[:code]
     resp[:code] = Api::V1::ErrorMessage::CODES[resp[:message]] || Api::V1::ErrorMessage::DEFAULT_CODE
end

render json: resp
 end

 def authenticate
    #authenticate_or_request_with_http_basic do |user, password|

      #File.write('test.txt', "USER: #{user}. PASS: #{password}")
         #@user && password == @user.secret_token #&&  @user.belongs_to_active_brand?
       true
      #end
    end

   def validate_request
      action = params[:action]
      klass = API_CMDS_LIST.select{ |klass, methods| methods.include?(action.to_sym) }.keys[0]

        @req = "Api::V1::#{klass}".constantize.new(send("# {action}_params").merge( {user: @user} ), request)

     if !@req.valid?
       err_msg = @req.errors.full_messages.first
       code = Api::V1::ErrorMessage::CODES[err_msg] || Api::V1::ErrorMessage::DEFAULT_CODE
      render json: { result: "error", msg: err_msg, code: code } and   return
     end
end

   end

and engine controller code is -

     class Api::V1::EngineController < Api::V1::MainController
    include Api::V1::ErrorMessage
    before_filter :validate_request



   API_CMDS_LIST["Engine"].each do |method|

    define_method(method) do
        response = @req.send(method)
           resulting_json(response)
    end
    end
   def users_add_params
        params.permit(:first_name,
              :last_name) 
  end
  end

but when i try to hit the endpoint "/users" with params {first_name : "satyam",last_name:"agrawal"} it gives me this error ---

Processing by Api::V1::EngineController#users_add as JSON Parameters: {"first_name"=>"satyam", "last_name"=>"agrawal"} Completed 500 Internal Server Error in 1ms (ActiveRecord: 0.0ms)

TypeError (no implicit conversion of nil into String):

activesupport (5.0.1) lib/active_support/security_utils.rb:23:in digest' activesupport (5.0.1) lib/active_support/security_utils.rb:23:inhexdigest' activesupport (5.0.1) lib/active_support/security_utils.rb:23:in variable_size_secure_compare' actionpack (5.0.1) lib/action_controller/metal/http_authentication.rb:75:inblock (2 levels) in http_basic_authenticate_with' actionpack (5.0.1) lib/action_controller/metal/http_authentication.rb:97:in call' actionpack (5.0.1) lib/action_controller/metal/http_authentication.rb:97:inauthenticate' actionpack (5.0.1) lib/action_controller/metal/http_authentication.rb:87:in authenticate_with_http_basic' actionpack (5.0.1) lib/action_controller/metal/http_authentication.rb:83:inauthenticate_or_request_with_http_basic' actionpack (5.0.1) lib/action_controller/metal/http_authentication.rb:71:in block in http_basic_authenticate_with' activesupport (5.0.1) lib/active_support/callbacks.rb:396:ininstance_exec' activesupport (5.0.1) lib/active_support/callbacks.rb:396:in block in make_lambda' activesupport (5.0.1) lib/active_support/callbacks.rb:169:incall' activesupport (5.0.1) lib/active_support/callbacks.rb:169:in block (2 levels) in halting' actionpack (5.0.1) lib/abstract_controller/callbacks.rb:12:incall' actionpack (5.0.1) lib/abstract_controller/callbacks.rb:12:in block (2 levels) in <module:Callbacks>' activesupport (5.0.1) lib/active_support/callbacks.rb:170:incall' activesupport (5.0.1) lib/active_support/callbacks.rb:170:in block in halting' activesupport (5.0.1) lib/active_support/callbacks.rb:454:incall' activesupport (5.0.1) lib/active_support/callbacks.rb:454:in block in call' activesupport (5.0.1) lib/active_support/callbacks.rb:454:ineach' activesupport (5.0.1) lib/active_support/callbacks.rb:454:in call' activesupport (5.0.1) lib/active_support/callbacks.rb:101:inrun_callbacks' activesupport (5.0.1) lib/active_support/callbacks.rb:750:in _run_process_action_callbacks' activesupport (5.0.1) lib/active_support/callbacks.rb:90:inrun_callbacks' actionpack (5.0.1) lib/abstract_controller/callbacks.rb:19:in process_action' actionpack (5.0.1) lib/action_controller/metal/rescue.rb:20:inprocess_action' actionpack (5.0.1) lib/action_controller/metal/instrumentation.rb:32:in block in process_action' activesupport (5.0.1) lib/active_support/notifications.rb:164:inblock in instrument' activesupport (5.0.1) lib/active_support/notifications/instrumenter.rb:21:in instrument' activesupport (5.0.1) lib/active_support/notifications.rb:164:ininstrument' actionpack (5.0.1) lib/action_controller/metal/instrumentation.rb:30:in process_action' actionpack (5.0.1) lib/action_controller/metal/params_wrapper.rb:248:inprocess_action' activerecord (5.0.1) lib/active_record/railties/controller_runtime.rb:18:in process_action' actionpack (5.0.1) lib/abstract_controller/base.rb:126:inprocess' actionview (5.0.1) lib/action_view/rendering.rb:30:in process' actionpack (5.0.1) lib/action_controller/metal.rb:190:indispatch' actionpack (5.0.1) lib/action_controller/metal.rb:262:in dispatch' actionpack (5.0.1) lib/action_dispatch/routing/route_set.rb:50:indispatch' actionpack (5.0.1) lib/action_dispatch/routing/route_set.rb:32:in serve' actionpack (5.0.1) lib/action_dispatch/journey/router.rb:39:inblock in serve' actionpack (5.0.1) lib/action_dispatch/journey/router.rb:26:in each' actionpack (5.0.1) lib/action_dispatch/journey/router.rb:26:inserve' actionpack (5.0.1) lib/action_dispatch/routing/route_set.rb:725:in call' rack (2.0.1) lib/rack/etag.rb:25:incall' rack (2.0.1) lib/rack/conditional_get.rb:38:in call' rack (2.0.1) lib/rack/head.rb:12:incall' rack (2.0.1) lib/rack/session/abstract/id.rb:222:in context' rack (2.0.1) lib/rack/session/abstract/id.rb:216:incall' actionpack (5.0.1) lib/action_dispatch/middleware/cookies.rb:613:in call' activerecord (5.0.1) lib/active_record/migration.rb:553:incall' actionpack (5.0.1) lib/action_dispatch/middleware/callbacks.rb:38:in block in call' activesupport (5.0.1) lib/active_support/callbacks.rb:97:inrun_callbacks' activesupport (5.0.1) lib/active_support/callbacks.rb:750:in _run_call_callbacks' activesupport (5.0.1) lib/active_support/callbacks.rb:90:inrun_callbacks' actionpack (5.0.1) lib/action_dispatch/middleware/callbacks.rb:36:in call' actionpack (5.0.1) lib/action_dispatch/middleware/executor.rb:12:incall' actionpack (5.0.1) lib/action_dispatch/middleware/remote_ip.rb:79:in call' actionpack (5.0.1) lib/action_dispatch/middleware/debug_exceptions.rb:49:incall' web-console (3.4.0) lib/web_console/middleware.rb:135:in call_app' web-console (3.4.0) lib/web_console/middleware.rb:28:inblock in call' web-console (3.4.0) lib/web_console/middleware.rb:18:in catch' web-console (3.4.0) lib/web_console/middleware.rb:18:incall' actionpack (5.0.1) lib/action_dispatch/middleware/show_exceptions.rb:31:in call' railties (5.0.1) lib/rails/rack/logger.rb:36:incall_app' railties (5.0.1) lib/rails/rack/logger.rb:24:in block in call' activesupport (5.0.1) lib/active_support/tagged_logging.rb:69:inblock in tagged' activesupport (5.0.1) lib/active_support/tagged_logging.rb:26:in tagged' activesupport (5.0.1) lib/active_support/tagged_logging.rb:69:intagged' railties (5.0.1) lib/rails/rack/logger.rb:24:in call' sprockets-rails (3.2.0) lib/sprockets/rails/quiet_assets.rb:13:incall' actionpack (5.0.1) lib/action_dispatch/middleware/request_id.rb:24:in call' rack (2.0.1) lib/rack/method_override.rb:22:incall' rack (2.0.1) lib/rack/runtime.rb:22:in call' activesupport (5.0.1) lib/active_support/cache/strategy/local_cache_middleware.rb:28:incall' actionpack (5.0.1) lib/action_dispatch/middleware/executor.rb:12:in call' actionpack (5.0.1) lib/action_dispatch/middleware/static.rb:136:incall' rack (2.0.1) lib/rack/sendfile.rb:111:in call' railties (5.0.1) lib/rails/engine.rb:522:incall' puma (3.7.1) lib/puma/configuration.rb:232:in call' puma (3.7.1) lib/puma/server.rb:578:inhandle_request' puma (3.7.1) lib/puma/server.rb:415:in process_client' puma (3.7.1) lib/puma/server.rb:275:inblock in run' puma (3.7.1) lib/puma/thread_pool.rb:120:in call' puma (3.7.1) lib/puma/thread_pool.rb:120:inblock in spawn_thread'

please help me to sort it out

lundi 13 mars 2017

Rails 3: Get helper_url from path

I am trying to get the helper_url from the current path. For example if I have the following route:

get "user/:user_id" => 'user#user_info', :as => 'user_information'

If I visit user/31221, is there any way for me to get the helper_url user_information or the string "user/:user_id" (not "user/31221") from the url?

I can get the controller and the action with Rails.application.routes.recognize_path(request.env['PATH_INFO']), but I am not able to get the rest of this information. I can do it with rake routes but I want to do this for a very specific logging purpose.

Imagine you have recently written a new language for Annkissam and implement the following solution

Imagine you have recently written a new language for Annkissam and collected all words into the Annkissam Dictionary. Similar to the English language, words can be categorized into nouns, verbs and articles. Below is the Annkissam Dictionary:

Nouns: "abcd", "c", "def", "h", "ij", "cde" Verbs: "bc", "fg", "g", "hij", "bcd" Articles: "a", "ac", "e"

However, the rules for creating a sentence in the Annkissam Language are very different. A valid sentence in the Annkissam Language should - have all its words present in the Annkissam Dictionary. - have a verb. - have a noun or have at least two articles.

Your task is to write a sentence composer which will take a string as an input and return all possible valid sentences. This composer keeps the characters of the string in the same order, while inserting at most one space between characters as necessary, to create valid words and a valid sentence.

For your convenience, we have provided some sample inputs and outputs. Input = "abcdefg", should return the following list: [ "a bc def g", "a bcd e fg", "abcd e fg" ]

Input = "abcc", should return the following list: ["a bc c"]

Input = "abcd", should return the following list: []

Rails how update the object with another action name?

Rails how update the object with another action name?

i'm trying to update the attribute track_number of Order object with a another action name so track is where the user find the Order and track_done is where he update. but the attribute did not update!

someone know why this happen?

here is controllers

 def track
    @order = current_seller.orders.find(params[:id])
    if current_seller.blank?
      # redirect_to new_user_changes_path(current_user)

 redirect_to :back


      flash[:error] = 'error.'
    end
  end



def track_done
  order = Order.find(params[:id])
  flash = if order.update_attributes(params[:order])
              { success: 'saved.' }
            else
              { error: 'error.' }
            end
    if request.xhr?
      render json: flash
    else
      redirect_to track_order_path(order), flash: flash
    end
  end



the routes



  resources :orders, only: [:index, :update, :destroy] do

    member do

get :track
put :track_done

    end

end

the view

 <div class="block  margin_top">

    <div class="subcontent">

            <%= form_for @order, :url => track_done_order_path(@order), method: :put,  html: { class: 'form-inline' } do |f| %>


  <%=order.track_number %>

   <label>Code</label> <%= f.text_field   :track_number %> 

  <%= f.submit "Ad",  class: "btn_grey" %>


   <% end %>



  </div>
 </div>

watir - ruby code " undefined method present? pr exist"

require 'rubygems' require "watir"

    browser = Watir::Browser.new :chrome,:switches => %w[--disable-notifications]
    i=0;
    begin

    #TODO logining to the facebook
    browser.goto 'linkedin.com'
    browser.text_field(:id => 'login-email').set 'ananthragavendra@gmail.com'
    browser.text_field(:id => 'login-password').set 'ru09ec32'
    browser.button(type: 'submit').click

    puts '**** linkedin logged in ****'

    sea = browser.div(:class => 'nav-search-bar')
    puts sea
    if sea.exits?
    browser.div(:class => 'nav-search-bar').click
    browser.div(:class => 'type-ahead-input-container').text_field.set 'wipro'
    browser.button(:class => 'nav-search-button').click
    puts '**** searched, the results for wipro is shown '
    else
    puts 'div not present'
    end


    side = browser.div(:class => 'right-rail search-right-rail')
    puts side
    if side.present?
    puts 'div present'
    side1 = browser.divs(:class => 'right-rail search-right-rail')
    else
    puts 'div not present'
    end



    #TODO exception handling
    rescue Exception => e
    p "Error Found..... #{e.message}"
    end

the error is thrown while executing the above simply, i am able to found the div in real time but i am unable to check the div using if commands, i have also tried some codes like exists.

---------------------


dimanche 12 mars 2017

Which way should I use for creating a page with rich HTML and CSS concepts?

Imagine I want to make a tutorial web application and you should make tons of content and tutorials for my users. In Ruby on Rails if I use CRUD system to make tutorials one by one and store in database, how can I get to rich HTML and CSS concepts while when I write description of tutorial inside a poor text_area and I can't make my page with HTML and CSS stuff to show great page. I just have very primary show page in show.html.erb and my content won't show great. For meeting my request which way do you suggest? Can I make my pages without CRUD and just playing with controllers and actions? Don't you think I will make tons of actions? Thanks

Ruby on Rails can't set my default index when running the localhost

I am using Rails 5.0.2 and Ruby 2.3.3 version. I created a controller using this command.

rails generate controller welcome index

It runs successfully. enter image description here

I'm trying to use the index.html.erb as my default route when the localhost:3000 is called in the url. So in routes.rb file I added the name of the controller action I created

root 'welcome#index'

In which also I checked it exists when I run the command

rake routes

But when I call the localhost:3000 using the changes I did it shows the following error.

enter image description here

How can I fix this? Are there any files I should edit if I change the routes.rb?

samedi 11 mars 2017

Rails Couldn't find Object without an ID

I'm trying to get the order of shop orders but Couldn't find Order without an ID error appear

ActiveRecord::RecordNotFound (Couldn't find Order without an ID)

i tried

 @order = Order.where("id = ? AND shop_id = ?", params[:id], @shop.id )

and another error

so, someone knows how to get the object from the associated objects?

class OrdersController < ApplicationController


def sold

  @shop = current_user.shop
@order =  @shop.orders.find(params[:id])

  end 
  end

vendredi 10 mars 2017

Error in Access-Control-Allow-Origin when Angular request to Rails

I'm using Angular 2 to make an API(rails) request. When I make the http request through angular, I get the following error: XMLHttpRequest cannot load https://api-url. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:4200' is therefore not allowed access. The response had HTTP status code 404. However, if I try to make a request through Postman or the browser itself, I don't get any error. The data is displayed normally angular code:

makeRequest() {
  let user = {"user": "user", "password": "password"};
  let headers: Headers = new Headers();
  headers.append('Authorization', 'Basic ' + btoa(user.user + ':'+user.password));
  headers.append('Content-Type', 'application/vn.api+json')
  let this.http.get(api-url, {headers: headers}).map(res => res.json()).subscribe(data => {
  this.data = data;
  })
 }

In my rails server i using the gem 'jsonapi-resources'to open AP. In my api controller, i have this code to authenticate and set headers to requests:

module Api
  class ApiController < JSONAPI::ResourceController
    prepend_before_action :set_headers, :authenticate

    def context
      { current_station: @user }
    end

    private

    def authenticate
      authenticate_or_request_with_http_basic do |token, _|
      @user = User.where(api_key: token).first
      end
    end

    def set_headers
      response.headers["Access-Control-Allow-Origin"] = "*"
    end
  end
end

When i make request in browser or using postaman, the header appears normally, but in Angular i have the error.

How to define local user in mysql database without entering a password?

How would create another user in my mysql database so another person who is working on my rails application can also get access to the server?

Most articles I found on the question tell me to type in a command like "mysql --user=root mysql -p" that requires a password (http://ift.tt/2mr4CA2)

Is there anyway around this?

Value not bind to the view from controller

I have two select tags as follow

 <%= f.select(:floor_id, ProjectFloor.find(:all,:order => "name ASC",:conditions => ["project_id = ?", @project.id]).collect{|b|[b.name, b.id]}, {:include_blank => 'Select'}) %>

 <%= f.select(:unit_id, @floor.collect{|b|[b.name, b.id]}, {:include_blank => 'Select'}) %>

When the user select the value on the first select tag called :floor_id then the value of the select tag data should be load to :unit_id select tag

I have try the following to read and fetch the data but. the floor_id always receiving null

My controller method is as follow :

@floor_id = params[:floor_id]
@project = Project.find(params[:project_id])
@proposed_customer = ProposedCustomer.new
@floor = ProjectFloorUnit.select_units(@project.id, @floor_id) 

The select unit method is work fine for static values so it must work if we pass the proper param.

Thanks in advances

jeudi 9 mars 2017

Rails strong params - using fields from has_many object

thanks a lot for your help.

In my rails project I have:

  • A location Model that has many :ads

    class Location < ApplicationRecord
        has_many :ads, :dependent => :destroy
    end
    
    
  • The Ad Model

  • In the controller developer_controller.rb I need to use with strong params the fields from location and ad

     params.require(:location).permit(:country, :location, :ads => [:remote, :days])
    
    

I don't know how to retrieve correctly the fields remote and days from the ad object.

Thanks a lot

Clinton

FOG: Creating instances in AWS fails

We are seeing below error when ever we try to create instances in AWS. Sometime it succeeds but most of the time it is throwing error. If we try to create 5 nodes it creates, 1 or 2 and fails on other.

Failure/Error: conn.servers.length
Excon::Error::Socket:
XML declaration allowed only at the start of the document (Nokogiri::XML::SyntaxError)

This is the way I'm creating the instances.

     Fog::Compute.new(
        :provider               => 'AWS',
        :region                 => @region,
         :use_iam_profile              => true
      )

 def valid_connection?(conn)
     conn.servers.length
     true
   rescue Excon::Errors::Forbidden, Excon::Errors::Unauthorized, Fog::Compute::AWS::Error
     false
   end

I tried to enable the debug logging as well but it does not show much info.

Preferred Log Level in Production

What is the most preferred log level in production Rails app. I just read in doc that Logging has a small impact on production.Currently the log level is set as info.

Multiple form in rails

Here I am trying to create a single form through which I want to save multiple data by one key press. For this I have created form in tabular format.

enter image description here

When i try to add date it is supplied inform of array to controller as below:-

enter image description here

But it gets rolled back if i try to save it. Here i am using nested form so that i can save multiple data to second form.

def new
    @purchase = Purchase.new
    @purchase_item = @purchase.purchase_items.build
    @item = Item.order(:name)
  end

  def create
    @purchase = Purchase.new(purchase_params)
    if @purchase.save
      flash[:success] = "Items added."
    else
      flash[:error] = "Items not added."
    end
    redirect_to :new_purchase
  end
 def purchase_params
    params.require(:purchase).permit(:vendor_id, purchase_items_attributes: [ :purchase_id , :item_id , :quantity, :unit_price ])
  end

So, Can anyone help me to solve this problem.

mercredi 8 mars 2017

Update nested Attributes on rails 3

In rails 4 usually updating a nested attributes we do:

and in rails 3? should user params.require?

def sent

@user.update_attributes(order_params)

  def order_params
  params.require(:user).permit( order_attributes: [:track_number])
end 

end




class User < ActiveRecord::Base

  has_many :orders

end

How to set website logo image on signup mail in rails?

I am using rails 5 when user is registered in my website i am sending an email for him for account approval.I want to set website logo with email. How we implement this in rails mailer view file enter image description here

Html for mail template

<!DOCTYPE HTML>
<html>
<title>nytApp Email</title>
    <head>
    </head>
    <body style="font-family: 'arial', sans-serif !important;   font-size: 14px;   line-height: 20px;  color:#3e3e3e; background-color: #f5f5f5; font-weight: 300;">
        <!-- Container Table -->
        <table cellpadding="0" cellspacing="0" border="0" width="100%">
            <tr>
                <td>
                    <table cellpadding="0" cellspacing="0" width="640" style="margin:0 auto; background:#fff;">
                        <tr>
                            <td style="border: 1px solid #f5cd8f;">
                                <table cellpadding="0" cellspacing="0" border="0" width="100%">
                                    <tr>
                                        <td style="padding: 25px 15px 20px; border-bottom: 1px solid #f5cd8f;">
                                            <table  align="center" cellpadding="0" cellspacing="0" border="0" width="100%">
                                                <tr>
                                                    <td><%= image_path('logo.png')%></td>
                                                    <td>
                                                        <table cellpadding="0" cellspacing="0" border="0" width="100%" style="font-weight: bold; font-size: 16px;">
                                                            <tr>
                                                                <td style="color: #ff5e00; font-weight: 300; font-size: 20px;">Welcome to Nytapp</td>
                                                            </tr>
                                                        </table>
                                                    </td>
                                                </tr>
                                            </table>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style="padding: 0 15px 20px;">
                                            <table  align="center" cellpadding="0" cellspacing="0" border="0" width="100%">
                                                <tr><td height="10"></td></tr>
                                                <tr>
                                                    <td>Thank you for signing up as Events Promoter!</td>
                                                </tr>
                                                <tr><td height="25"></td></tr>
                                                <tr>
                                                    <td>You are ready to start posting your parties for free. Login to the portal by clicking on the link below:</td>
                                                </tr>
                                                <tr><td height="10"></td></tr>
                                                <tr>
                                                    <td><a href="http://ift.tt/2n8CykL" style="color: #00a8ff;">http://ift.tt/2n1u9mm;
                                                </tr>
                                                <tr><td height="10"></td></tr>
                                                <tr>
                                                    <td>If the above URL does not work try copying and pasting it into your browser.</td>
                                                </tr>
                                                <tr><td height="8"></td></tr>
                                                <tr>
                                                    <td>If you encounter any problem, please contact us at <a href="mailto:admin@nytapp.com" style="color: #333; font-weight: bold; text-decoration: none;">admin@nytapp.com</a></td>
                                                </tr>
                                                <tr><td height="25"></td></tr>
                                                <tr>
                                                    <td>Thank you,</td>
                                                </tr>
                                                <tr>
                                                    <td>The Nytapp team</td>
                                                </tr>
                                                <tr><td height="30"></td></tr>
                                            </table>
                                        </td>
                                    </tr>
                                    <tr>
                                        <td style="border-top: 1px solid #f5cd8f; vertical-align: middle;  padding: 10px 15px;">
                                            <table cellpadding="0" cellspacing="0" border="0" width="100%">
                                                <tr>
                                                    <td>
                                                        <%= image_path('logo.png') %>
                                                    </td>
                                                </tr>
                                            </table>
                                        </td>
                                    </tr>
                                </table>
                            </td>
                        </tr>
                    </table>
                </td>
            </tr>
        </table>
    </body>
</html>

Rails - Update attributes with best in place gem

Using best in place to update a attribute in a Order form rails spit out undefined methodupdate_attributes' for #`

the form is not on a update action but in a sold action, so the form must be inside of a update action?

          <%= best_in_place order, :track_number, :as => :input, :nil => "Track code", :url => sold_order_path(order)%> 



        Mark as:

            <%= link_to "Sent",  sent_order_path(order), :class => 'btn btn_small' %>






def sold
    @q = Order.where('seller_id = ? and status = ?', current_vitrine.id, params[:status] || Order.statuses[0]).ransack(params[:q])
    @orders = @q.result(distinct: true).paginate(page: params[:page], per_page: 22)

 @order = Order.find_by_id(params[:id]) 


     respond_to do |format|
      if Order.where('seller_id = ? and status = ?', current_vitrine.id, params[:status] || Order.statuses[0]).update_attributes(params[:order])
        format.html { redirect_to :back, notice: 'Comment was successfully updated.' }
        format.json { respond_with_bip(@order) }
      else
        format.html { render action: 'sold' }
        format.json { respond_with_bip(@order) }
      end
    end

  end

How can I call a channel method in a rails controller?

I have an ActionCable method that subscribes the user. If a new convo is started, I want to subscribe the user to the new channel as well. I can't figure out the proper syntax for calling a channel method in a controller.

channel/msgs_channel.rb

class MsgsChannel < ApplicationCable::Channel  
  def subscribe(convo_id)
      stream_from "msg_channel_#{convo_id}"
  end
end

convos_controller.rb

def create
  @convo = Convo.create!({sender_id: @sender_id, recipient_id: @recipient_id})
  ActionCable.server.subscribe(@convo.id)
end

In my convos controller, create method, I have tried several things:


ActionCable.subscribe(@convo.id)

error: NoMethodError (undefined methodsubscribe' for ActionCable:Module)`


ActionCable.msgs.subscribe(@convo.id)

error: NoMethodError (undefined methodmsgs' for ActionCable:Module):`


  App.msgs.subscribe(@convo.id)

error:NameError (uninitialized constant ConvosController::App):


MsgsChannel.subscribe(@convo.id)

error:NoMethodError (undefined methodsubscribe' for MsgsChannel:Class`


ActionCable.server.subscribe(@convo.id)

error:NoMethodError (undefined methodsubscribe' for #):`

Deleting polymorphic associations

I have implemented a favoriting system for my rails app by following this great article.

Here is my set up:


favorite.rb

class Favorite < ActiveRecord::Base
  belongs_to :user
  belongs_to :favorited, polymorphic: true
end


project.rb

class Project < ActiveRecord::Base
    belongs_to :user

    has_many :favorites, as: :favorited
    has_many :fans, through: :favorites, source: :user 


user.rb

class User < ActiveRecord::Base
  has_many :listings
  has_many :projects
  has_many :favorites
  has_many :favorite_listings, through: :favorites, source: :favorited, source_type: 'Listing'
  has_many :favorite_projects, through: :favorites, source: :favorited, source_type: 'Project'


favorite_projects_controller.rb

class FavoriteProjectsController < ApplicationController
  before_action :set_project
  # before_action :correct_user
  # before_action :authenticate_user!

  def create
    if Favorite.create(favorited: @project, user: current_user)
      redirect_to @project, notice: 'Project has been favorited'
    else
      redirect_to @project, alert: 'Something went wrong...*sad panda*'
    end
  end

  def destroy
    Favorite.where(favorited_id: @project.id, user_id: current_user.id).first.destroy
    redirect_to @project, notice: 'Project is no longer in favorites'
  end

  private

  def set_project
    @project = Project.find(params[:project_id] || params[:id])
  end
end


Here is the problem.

I had some favorited projects.

I used Project.delete_all to delete my projects while certain projects were still "favorited" but now I get an error:

 ActionView::Template::Error (undefined method `favorite_projects' for nil:NilClass):

I'm sure If I had "unfavorited" all those projects before deleting them, this error would not come up.

Does anyone have an idea on how to fix this?

Ruby on Rails: Creating a new children instance using the parent's id/Working with associated classes

One of my goal on this web app project is to make each tailor add or create products. So I made a MCV structure from scratch for the Tailor for the sign up page. And then I scaffold the Product since basic CRUD functions will be used by the Tailor to create a product. And then I put them into has_many/belongs_to relationship. I generated a migration which adds a column tailor_id into the Product class. Then I put these nested routes:

resources :tailors do
   resources :products
end 
resources :products #this is for debugging for whether a customer can see all the Products created by all the Tailors

then I ran rake routes and checked which path I can use to create a product with a given tailor_id then I decided to use the /tailors/:tailor_id/products/new. So I added a code which is a link in my tailor show page:

<%= link_to 'Add Product', new_tailor_product_path(@tailor.id) %>

and the I edited the new and create functions in the products_controller since the path is directed there) like this:

  def new
    @tailor = Tailor.find(params[:tailor_id])
    @product = @tailor.Product.new(params[@tailor])
  end

  def create
    @tailor = Tailor.find(params[:tailor_id])
    @product = @tailor.Product.new()
    @product.product_name = params[:product][:product_name]
    @product.product_description = params[:product][:product_description]
    @product.price = params[:product][:price]
    @product.tailor_id = params[:product][@tailor]
    @product.save
    redirect_to "/tailors/#{@tailor}"
  end

but the error says Undefined method 'Product' that occurs in the where the @product = @tailor.Product.new(params[@tailor])is

I don't really understand why is this an error because I'm pretty sure I called the class right (It's been taught to us that classes must begin with capital letter and is singular) and it's clear that I'm not calling a method.

Please explain the concept of calling the parent class and its data. Am I not allowed to call the Tailor class and its data inside the product_controller in this case? Is my approach wrong or am I in the right direction?

Also, other Remarks and Error corrections about the other parts of my codes are welcomed

Upload file to custom route rails carrier wave using form_tag

I have a post method that I wish to use to change the profile picture of the user.

routes.rb

  post "users/change_profile_picture", to: 'users#change_profile_picture'

form part of the show.html.erb

<%=form_tag(users_change_profile_picture_path, :method=>'post',remote: true,authenticity_token: true, :multipart => true) do%>
        <%= file_field_tag "profile" %>
        <%= text_field_tag "display_name" %>
         <%= submit_tag 'Submit' %>
<% end %>

If I submit a text with that form everything is working fine(show.js.erb gets executed and updates the page), but when I click submit with a file it crashes. The show.js.erb doesn't get executed anymore. All I get is a no content header in rails console.

I can upload a file using form for @user, but how do I upload one using form_tag and my method?

change_profile_picture method

def change_profile_picture
    @user = cp_params[:display_name]
      respond_to do |format|
        format.html
        format.js { render 'users/show.js'}
      end
  end

params

private
  def cp_params
      params.permit(:profile,:authenticity_token,:utf8, :display_name, :commit)
  end

mardi 7 mars 2017

Rails 3 to Rails 4

There was an error while trying to load the gem 'active_record_foreign_keys'. (Bundler::GemRequireError). Gem Load Error is: undefined method to_sql' for classActiveRecord::ConnectionAdapters::TableDefinition' Did you mean? to_s

Relationship between student, enrollment, course and section table

I want to get record student enroll the specific course in which section ??? Because one course taught in multiple sections.

class Student < ActiveRecord::Base
    has_many :enrolments
    has_many :courses, through: :enrolment
end
class course < ActiveRecord::Base
    has_many :enrolment
    has_many :students, through: :enrolment
    has_many :sections
end
class enrolment < ActiveRecord::Base
    belongs_to :students
    belongs_to :courses
end
class Section < ActiveRecord::Base
    belongs_to :courses
end

Relationship

Student.first.courses.first.sections

Due to this relationship i got multiple sections. But I want to get single section in which student enroll the specific course ??? Here I am confused do you think this design is good? If not please provide some suggestions.