Tuesday, November 22, 2016

How to iterate through an array with React (Rails) | Fixed issues

How to iterate through an array with React (Rails) | Fixed issues


How to iterate through an array with React (Rails)

Posted: 22 Nov 2016 07:49 AM PST

I just started to learn React and I am trying to figure out how to find a specific value I am looking for. Just like you have the each.do method in Ruby and you can iterate through an array, I'm trying to do that with React.

class Gallery extends React.Component {    render () {      // debugger;      return (        <div>        <img> {this.props.gallery.thumbnail_url} </img>        </div>      )    }  }  

I am trying to access the thumbnail._url and when using the debugger, I am not able to access all the objects and images. I thought of this.props.gallery.object.thumbnail_url and other ideas but I am not really sure of the best way! debugger information

Sort rails results by price

Posted: 22 Nov 2016 07:40 AM PST

I'm wanting to sort this:

  @results = Table.where(merchant_deep_link: results)  

via search_price (a column that sits inside the Table table)

  @results = Table.where(merchant_deep_link: results).order(:search_price)  

However in my view i have this:

<%= @results.first.search_price %>  

Which didn't return a low price, It returned a random price in the middle (low price being 69.00 and it returned 103.00)

Any ideas?

Thanks

Getting the individual checkbox value in JQuery

Posted: 22 Nov 2016 07:47 AM PST

I have several checkboxes and have a JQuery function that I want to print out the value I give each checkbox when I click on the checkbox. However, 1 keeps printing out. I assign each checkbox an item.id based on a primary key from my db using Rails. Here is my code

<script>  $(document).ready(function(){      $('input[type="checkbox"]').on("change", function() {          var hall_id = $(this).val(); // here is where I want to get the value that I assigned to the checkbox      if (this.checked) {          console.log( hall_id );       } else {          console.log( hall_id );      }  });  });  </script>        <%= link_to "Logout", root_path %>    <h1>Hello <%= @user.first_name%> <%= @user.last_name%></h1>    <%= form_for @item do |f| %>    <%= f.label :to_do %>:    <%= f.text_field :to_do %><br />    <%= f.hidden_field :email, :value => @user.email%>        <%= f.submit %>  <% end %>    <% @items.each do |item|%>      <%if item.email == @user.email%>          <%= form_for @item do |f| %>        <%= item.id%>              <%= f.check_box :to_do, :value => item.id%>  //This is where I assign the value for the check box              <%= item.to_do%><br />          <% end %>      <%end%>  <%end%>  

enter image description here In the image I am trying to print out the number by the checkbox(item.id), but in the console it only prints out 1

Creating a class namespace from a variable

Posted: 22 Nov 2016 07:40 AM PST

Is there a way I can compose a class namespace from a variable?

For example, let's say I want to catch an exception that is inside Foo::Bar::MyException, but Bar is in a variable (a = :Bar).

Would that be something like Foo::@a::MyException?

Using .where in Rails Controller Method

Posted: 22 Nov 2016 07:18 AM PST

I have a Statistics page and currently have an Items Bought and an Items Sold table. The Items Bought table is working just fine, however I am having some issues with the Items Sold table. There is a boolean in my DB for SOLD and I want the count to display for all those items marked as TRUE. The current .where statements have date statements as well and I'm not sure how to incorporate both of them with it erroring out.

items_controller:

def statistics    @items = Item.all    @items_day = Item.all.where('created_at >= ? AND created_at <= ?', Time.zone.now.beginning_of_day, Time.zone.now.end_of_day)    @items_week = Item.all.where('created_at >= ? AND created_at <= ?', Time.zone.now.beginning_of_week, Time.zone.now.end_of_week)    @items_month = Item.all.where('created_at >= ? AND created_at <= ?', Time.zone.now.beginning_of_month, Time.zone.now.end_of_month)      @items_sold = Item.all.where(:sold => true)    @items_sold_day = Item.all.where(:sold => true 'created_at >= ? AND created_at <= ?', Time.zone.now.beginning_of_day, Time.zone.now.end_of_day)    @items_sold_week = Item.all.where(:sold => true 'created_at >= ? AND created_at <= ?', Time.zone.now.beginning_of_week, Time.zone.now.end_of_week)    @items_sold_month = Item.all.where(:sold => true 'created_at >= ? AND created_at <= ?', Time.zone.now.beginning_of_month, Time.zone.now.end_of_month)  end  

statistics.html.erb

<h3 id="subtitle">Items Bought</h3>  <table align="center" style="width: 95%" class="table table-striped table-bordered">    <thead>      <tr>        <th>Total</th>        <th>Today</th>        <th>Week</th>        <th>Month</th>      </tr>    </thead>      <tbody>      <tr>        <td><%= number_with_delimiter(@items.count) %></td>        <td><%= @items_day.count %></td>        <td><%= @items_week.count %></td>        <td><%= @items_month.count %></td>      </tr>    </tbody>  </table>    <h3 id="subtitle">Items Sold</h3>  <table align="center" style="width: 95%" class="table table-striped table-bordered">    <thead>      <tr>        <th>Total</th>        <th>Today</th>        <th>Week</th>        <th>Month</th>      </tr>    </thead>      <tbody>      <tr>        <td><%= number_with_delimiter(@items_sold.count) %></td>        <td><%= @items_sold_day.count %></td>        <td><%= @items_sold_week.count %></td>        <td><%= @items_sold_month.count %></td>      </tr>    </tbody>  </table>  

Ansible error when doing bundle task

Posted: 22 Nov 2016 07:01 AM PST

I am trying to set the env variables with export in ansible, bundle install works but when i do the bundle exec rake db:reset i am getting this error

changed: [54.196.132.12] => (item=export DB_HOST='ansibledataloading.c4hhvnlgssle.us-east-1.rds.amazonaws.com')  changed: [54.196.132.12] => (item=export ELASTICACHE_ENDPOINT='ansibledataloading1.2hkoge.0001.use1.cache.amazonaws.com:1211')  changed: [54.196.132.12] => (item=bundle exec bundle install)  failed: [54.196.132.12] (item=bundle exec rake db:reset) => {"changed": true, "cmd": "cmd=bundle exec rake db:reset", "delta": "0:00:06.263417", "end": "2016-11-22 09:51:44.995892", "failed": true, "item": "bundle exec rake db:reset", "rc": 1, "start": "2016-11-22 09:51:38.732475", "stderr": "rake aborted!\nLoadError: Could not load 'active_record/connection_adapters/_adapter'. Make sure that the adapter in config/database.yml is valid. If you use an adapter other than 'mysql', 'mysql2', 'postgresql' or 'sqlite3' add the necessary adapter gem to the Gemfile.\n/home/ubuntu/sims/config/environment.rb:5:in `<top (required)>'\nLoadError: cannot load such file -- active_record/connection_adapters/_adapter\n/home/ubuntu/sims/config/environment.rb:5:in `<top (required)>'\nTasks: TOP => db:reset => environment\n(See full trace by running task with --trace)", "stdout": "", "stdout_lines": [], "warnings": []}  

the code looks like this

- name: Run Bundle install/db:reset/ And create views    shell: chdir=/home/ubuntu/sims cmd={{item}}    with_items:      - export DB_HOST='{{hostvars.localhost.rds.instance.endpoint}}'      - export ELASTICACHE_ENDPOINT='{{hostvars.localhost.elastic_data.elasticache.data.CacheNodes[0].Endpoint.Address}}:1211'      - bundle exec bundle install      - bundle exec rake db:reset    #environment:      # DB_HOST: '{{hostvars.localhost.rds.instance.endpoint}}'      #ELASTICACHE_ENDPOINT: '{{hostvars.localhost.elastic_data.elasticache.data.CacheNodes[0].Endpoint.Address}}:1211'  

i tried the environment module but it had same error so i changed it to export. How can i achieve the environment variables set dynamically? what is the error i am getting?

I logged into the ec2 instance and did export of env variables and did bundle exec rake db:reset and it works there.

Rails error - Booking unsuccessful

Posted: 22 Nov 2016 07:03 AM PST

I'm building an Event app using Rails. I've recently changed around my bookings controller to accomodate events which are free. This side of the app seems to work fine but when I try a test booking for a paid event the app defaults to 'booking unsuccessful' after I complete the payment submission form.

I'm not really sure why this is happening. Here's my controller logic -

def new            @event = Event.find(params[:event_id])          @booking = Booking.new          @booking.user = current_user            end        def create          @event = Event.find(params[:event_id])          @booking = Booking.new(booking_params)          @booking.user = current_user                  if                   @booking.save                  flash[:success] = "Your place on our event has been booked"                  redirect_to event_booking_path(@event, @booking)              else                  flash[:error] = "Booking unsuccessful"                  render "new"              end        end        def show          @event = Event.find(params[:event_id])          @booking = Booking.find(params[:id])      end          def update            if @booking.update(booking_params)              redirect_to event_booking_path(@event, @booking) , notice: "Booking was successfully updated!"          else              render 'new'          end      end              private        def booking_params          params.require(:booking).permit(:stripe_token, :booking_number, :quantity, :event_id, :stripe_charge_id, :total_amount)      end  

And in my model I have this -

Booking.rb

def booking          # Don't process this booking if it isn't valid          self.valid?              if booking.is_free?              self.total_amount = event.price_pennies.nil?              save!            end                  begin                          self.total_amount = event.price_pennies * self.quantity                          charge = Stripe::Charge.create(                              amount: total_amount,                              currency: "gbp",                              source: stripe_token,                               description: "Booking created for amount #{total_amount}")                          self.stripe_charge_id = charge.id                self.booking_number = "MAMA" + '- ' + SecureRandom.hex(4).upcase                          save!                      rescue Stripe::CardError => e                      errors.add(:base, e.message)                      false                  end      end  

So, for some reason its not saving or there's something else not right. Any assistance appreciated.

Rails 4: how do I generate an error message in login view?

Posted: 22 Nov 2016 06:54 AM PST

Here in the login view I have this code:

<p id="notice"><%= notice %></p>    <h1>Log In</h1>    <%= form_tag({controller: "sessions", action: "create"}) do %>  <% if false %>  <% if errors.any? %>    <div id="error_explanation">      <h2><%= pluralize(errors.count, "error") %> unseccessful:</h2>        <ul>      <% errors.full_messages.each do |message| %>        <li><%= message %></li>      <% end %>      </ul>    </div>  <% end %>  <% end %>      <div class="field">      <%= label_tag :username %><br/>      <%= text_field_tag :username, params[:username] %><br/>    </div>    <div class="field">      <%= label_tag :password %><br/>      <%= password_field_tag :password %><br/>    </div>    <div class="actions">      <%= submit_tag "Log In" %>    </div>    <% end %>  

and if I enter incorrect user information it should give some notice from the controller:

def create        user = User.find_by_username(params[:username])      respond_to do |format|        if user && user.password == params[:password]          session[:user_id] = user.id          format.html { redirect_to root_url, notice: 'Logged In successfully' }          format.json { render :index, status: :created, location: @session }        else            format.html { render :new, notice: "Email or password is invalid" }          format.json { render json: @session.errors, status: :unprocessable_entity }          #flash.now.alert = "Email or password is invalid"          #render "new"        end      end    end  

but instead it just reloads the login page with no notice or error message whatsoever. I'm new to Rails, do you have any idea what I can do?

Why do I receive usage info when trying to run bin/rails db:create?

Posted: 22 Nov 2016 06:15 AM PST

When I try to use bin/rails db:create (or bundle exec rails db:create), I receive the usage info for rails new.

I'm using chruby with version 2.3.3 and Rails 5.0.0.1.

The goal here is just to create the databases....what's going on?

Method for destroying activity

Posted: 22 Nov 2016 07:31 AM PST

I am using the acts_as_votable and public_activity gems, and want to remove activities when posts are 'unliked'. The public_activity docs specify using dependent: :destroy... however, there is no model for 'likes', and so there is nothing to destroy. The docs don't seem to include a method for manually removing activity on other actions.

For anyone familiar with the public_activity gem, have you ever run into this issue and how did you solve it?

Multiple upload paperclip error

Posted: 22 Nov 2016 07:07 AM PST

I m trying to implement multiple upload images for my app with paperclip like this link

Actually simple upload work, but if I try to implement an array I have an error.

undefined method `create' for Paperclip::Attachment:0x007f33ecb3bd30

campings_controller.rb

def create            @camping = Camping.new((camping_params).merge(:user_id => current_user.id))          respond_to do |format|          if @camping.save            format.html { redirect_to @camping, notice: 'Camping was successfully created.' }            format.json { render :show, status: :created, location: @camping }          else            format.html { render :new }            format.json { render json: @camping.errors, status: :unprocessable_entity }          end        end      end        def update      @camping = Camping.find(params[:id])       if params[:image]          params[:image].each do |image|            @camping.create(image: image)          end        end        end  

_edit.html.erb

<%= file_field_tag "image[]", type: :file, multiple: true %>  

camping.rb

has_attached_file :image, default_url: "/images/missing.jpg"    validates_attachment_content_type :image, :content_type => ["image/jpg", "image/jpeg", "image/png", "image/gif"]  

Initialize multiple selections in select2

Posted: 22 Nov 2016 05:53 AM PST

I'm developing a multiple selection in Select2 4.0 and Rails 4.2.7.1. The code saves the right value in the database, but I've noticed a problem: it loses all value selection after a failed validation. How could i initialize all the value previously selected after a page reload? Thanks.

This is the current select2 declaration:

$(select_report).select2({  ajax: {  url: '/vaccination_plans/index_json',  dataType: 'json',  data: function (params) {  return {    q: params.term  };  },  processResults: function (data, params) {  return {    results: data  };  },    cache: true  },  templateResult: function (data) {    return data.vaccine_name;  },  templateSelection: function (data) {    return data.vaccine_name;  },  minimumInputLength: 3  });  

Bitbucket Authentication failed on pushing existing project

Posted: 22 Nov 2016 05:57 AM PST

This is the error on my terminal:

Authentication failed for 'https://bitbucket.org/railstutorial/sample_app_4th_ed.git/'  

This is what I did:

git remote add origin ssh://git@bitbucket.org/kboygitgit/sample_app.git  git push -u origin master  

then it asked for my username and password

then the error showed up

remote: Unauthorized  fatal: Authentication failed for 'https://bitbucket.org/railstutorial/sample_app_4th_ed.git/'  

Using assert_select div to test for the number of error messages

Posted: 22 Nov 2016 05:45 AM PST

I am trying to test for the correct number of error messages on a page using assert_select but I am not sure what the appropriate div.alert combination is.

Rails, minitest: How to test the output of a controller

Posted: 22 Nov 2016 06:12 AM PST

My controller looks like this:

class CalculatorController < ApplicationController      def calculate      money = params[:money].to_f     @worktime =  divide(money, 25)    end      private      def divide(money, worktime)      output = money/worktime    end  end  

I wrote a Test like this:

require 'test_helper'    class CalculatorControllerTest < ActionDispatch::IntegrationTest    test "response" do      get calculate_path      assert_equal 200, response.status    end  end  

This test passes. Now, I want to write a test, to check, whether the output is correct. I tried this:

require 'test_helper'    class CalculatorControllerTest < ActionDispatch::IntegrationTest    test "response" do      get calculate_path(money: 25)      assert_equal 200, response.status      assert_equal 1, @response.worktime    end  end  

But this error occurs: NoMethodError: undefined methodworktime'`

How do I test the output of the controller? ( In my case @worktime)

Relation passed to #or must be structurally compatible. Incompatible values: [:references]

Posted: 22 Nov 2016 05:06 AM PST

I have two queries, I need an or between them, i.e. I want results that are returned by either the first or the second query.

First query is a simple where() which gets all available items.

@items = @items.where(available: true)  

Second includes a join() and gives the current user's items.

@items = @items.joins(:orders).where(orders: { user_id: current_user.id})  

I tried to combine these with Rails' or() method in various forms, including:

@items = @items.joins(:orders).where(orders: { user_id: current_user.id})       .or(@items.joins(:orders).where(available: true))  

But I keep running into this error and I'm not sure how to fix it.

Relation passed to #or must be structurally compatible. Incompatible values: [:references]  

Rails password protected page with custom lock screen and no redirects

Posted: 22 Nov 2016 04:28 AM PST

Squarespace has a nice lock screen mechanic that I am trying to duplicate in my rails app:

User navigates to url (e.g. http://localhost:3000/customs) but page is locked so user sees lock screen (icon and password input field below the icon - no username field, just password). URL remains the same even though the page is locked (i.e. no redirects)

User enter's the password, the lock screen fades out and the page content fades in all without the url changing.

Password is saved until browser cache clear so user doesn't see lock screen upon re-entering URL at a later date.

I can't work out how to do this in my rails app. The app uses sites wide Devise user login for authentication but require's signup and view (url) redirects which I am keen to avoid for this page.

I have also tried http authentication but would ideally like a full page (and customisable) lock screen.

Any ideas much appreciated

How to show current user's tag_id on a page called map while using ROR?

Posted: 22 Nov 2016 07:13 AM PST

I am trying to show the current user's tag_id and the datetime of the detection on a new page(index.html.erb) that is in a folder called map in the views folder. I have tables called detections, lendings, users, and rfid_tag. these are the relationships.

User:

class User < ActiveRecord::Base    has_many :lendings    has_many :rfid_tags, :through => :lendings  end  

RfidTag (has a tag_id):

class RfidTag < ActiveRecord::Base    has_many :detections    has_many :sensors, :through => :lendings    has_many :users, :through => :lendings  end  

Lending:

class Lending < ActiveRecord::Base    belongs_to :rfid_tag    belongs_to :user  end  

detection (has the datetime):

class Detection < ActiveRecord::Base    belongs_to :sensor    belongs_to :rfid_tag  end  

How can I do this?

Connection reset by peer - SSL_connect error in production when using Bitly

Posted: 22 Nov 2016 04:01 AM PST

I am using bitly url in my application in 2 cases. In one case I am using it through jQuery as:

  function get_short_url(long_url, login, api_key, func)  {      $.getJSON(          "http://api.bitly.com/v3/shorten?callback=?",           {               "format": "json",              "apiKey": api_key,              "login": login,              "longUrl": long_url          },          function(response)          {              func(response.data.url);          }      );  }  

and in other case I am using bitly gem with version 1.0.2. For this I am adding

view:

<%= f.input :link_placeholder, :as => :text, :label => false, :input_html => { :id => 'copy_link', :class => '', :value => "#{get_bitly_url(user_report_url(@user, @report))}", :rows => 2, :cols => 30, :maxlength => 490} %>  

controller:

  def show      @report = Report.find(params[:id])      @bitly_url = get_bitly_url("#{user_reports_url}/#{@report.id}")          respond_to do |format|        format.html # show.html.erb        format.xml  { render :xml => @report }      end    end    def get_bitly_url(url)      if Rails.env.development?        return url      else        bitly = Bitly.new('myapp', 'R_e2pd1dca0442a20a2qwqw59156e3260d')        bitly.shorten(url).short_url      end    end  

the above 2 are working fine in development mode and rails production mode and I also tried in AWS EC2 instance with Apache and Phusion, it is working great but it is not working in the main production server where the domain name is mentioned in the url with "https".

These are the errors I am getting:

Errno::ECONNRESET (Connection reset by peer - SSL_connect):
app/controllers/reports_controller.rb:342:in get_bitly_url'
app/controllers/reports_controller.rb:35:in
show'

The url mentioned in show is coming from js file as mentioned above.

Please help me to get out of this error.

Ajax Bad Request 400 Rails

Posted: 22 Nov 2016 04:07 AM PST

I'm getting bad request error 400 using Ajax on Rails. When i submit my form I have a string to send as parameter from Jquery and i want to retrieve it from params[:assignee] so i can extract the string and save it through my controller. My controller:

    def create      @task = Task.new(task_params)      @task.user = current_user      username = params.permit[:assignee]      @task.assignee = username        #set_category      respond_to do |format|        if @task.save          format.html { redirect_to tasks_url, notice: 'Task was successfully created. '+task_params.inspect}            #format.html { redirect_to @task, notice: 'Task was successfully created.' }          format.json { render :show, status: :created, location: @task }        else          format.html { render :new }          format.json { render json: @task.errors, status: :unprocessable_entity }        end      end    end    def task_params    params.require(:task).permit(:owner, :value, :completed, :category, :date, :assignee)    end  

And this is my JS:

 $( "#new_task" ).submit(function() {      alert("form: "+assignee);    //event.preventDefault();   $.ajax({     url: "/tasks",     type: "POST",     data: {assignee},     dataType: "json",     success: function(data) {         alert('successfully');       },      error: function(xhr, textStatus, error) {       alert(xhr.statusText+""+textStatus+""+error);    }     });  });  

assignee is an username selected in a jquery auto-complete form:

select: function(event, ui) {      var terms = split(this.value);      // remove the current input      terms.pop();      // add the selected item      terms.push(ui.item.value);      // add placeholder to get the comma-and-space at the end      terms.push("");      this.value = terms.join("");      assignee=this.value;      $('input[name=commit]').prop("disabled",false);        return false;  }  

My root is "task/" where you can see saved tasks and a form to create a new one. I searched a lot on the net and I tried them all. How can I do? Thanks so much

model Shop::Product looking table shop_products. Why?

Posted: 22 Nov 2016 03:39 AM PST

I have following model models/shop/product.rb

class Shop::Product  end  

I generated migration

def change      create_table :products do |t|        # ...        t.timestamps      end    end  

I create new product and display error UndefinedTable: ERROR: "shop_products"

Quotes role in setting ruby code inside javascript variable

Posted: 22 Nov 2016 03:24 AM PST

I am trying to set a javascript variable to link_to rails helper like this:

var link = '<%= link_to "Book 1", user_book_path(29), class: "btn btn-success btn-sm", target: "_blank" %>'  

It works great like this, but the problem is that I get this link_to as a string from ajax request and the single quotes around are replaced by double quotes and vice versa. My result string is:

"<%= link_to 'Book 1', user_book_path(29), class: 'btn btn-success btn-sm', target: "_blank" %>"  

Of course, it doesn't work as expected (link isn't generated, the string remains just a string). How do I fix this quotes problem?

Google translate free api resposne to JSON Array in ruby

Posted: 22 Nov 2016 05:38 AM PST

I'm working on a simple API in ruby on rails, which will connect with Google translate API (using the simple trick to get a response for free) and process the output.

My request looks like i.e.:

https://translate.googleapis.com/translate_a/single?client=gtx&sl=en&tl=es&dt=t&q=build

and responses I'm getting from Google server is as follows (can't get a json formatted response, as setting client to 'p' no longer works)

[[["construir","build",,,1]],,"en"]

In java I can easily process that response by creating a JSONArray object, however I can't find a way to do so in my ruby on rails app.

I'm using rest-client to make a request

@response=RestClient.post('http://myrequestblabla')  @jsonArray = JSON.parse(response.body)  

and last line fails with

A JSON text must at least contain two octets!

Is there anyway to process a response like that? Ideally to break it into JSONArray, but will be happy to see any neat solution.

Thanks,

Max years allowed parameter for credit card field

Posted: 22 Nov 2016 04:27 AM PST

I am working in a rails application in c9. In my project I entered the credit card fields with this code at the end:

 <%= select_year nil, {start_year: Date.today.year, end_year: +15}, {name: nil, id: "card_year"}%>  

I get this error message: There are too many years options to be built. Are you sure you haven't mistyped something? You can provide the :max_years_allowed parameter.

How is this :max_years_allowed parameter written in code to bridge this problem? Any expert advice?

Ordering ActiveRecord instances according to their children's specific attributes

Posted: 22 Nov 2016 05:31 AM PST

I have two ActiveRecord models - Residence and Apartment.

class Residence < ActiveRecord::Base    has_many :apartments  end    class Apartment < ActiveRecord::Base    belongs_to :residence  end  

apartments table has fields price_from (unit price) and area. so total price for an apartment is price_from*area

I've also defined an instance method for residences

def min_price_for_apartment    apartments.minimum("price_from*area")  end  

I am able to sort residences in ascending/descending order with calling this scope.

#scope: with_children, -> { where(published: true).includes(:apartments).joins(:apartments) }    scope: sort_by_unit_price_asc, -> { with_children.order('apartments.price_from') }  # scope: sort_by_unit_price_asc, ->{adding desc to the end of previous scope}  

What should I do to sort residences by their minimum apartment price?

UPDATE: i've found a solution with pure sql, now need to translate it to AR

# select residences.name from residences inner join apartments on residences.id = apartments.residence_id group by (residences.id) order by min(apartments.price_from*apartments.area)       name      -----------   Lorem   Ipsum   Quod   Maritimus   Amet  (5 rows)  

P.S. I am aware of other related questions and answers on SO, but none of them helped me. I am also aware of to implement a frontend based solution, with passing such values to data-attributes and sort according to them.

Selecting one of a has_many relation in Rails

Posted: 22 Nov 2016 03:16 AM PST

What is the preferred way of selecting a specific record out of a has_many relation for a specific model in Rails? (I'm using Rails 5.)

I have a model User and a model Picture which are related via the following code:

class User < ApplicationRecord    has_many :pictures, as: :imageable    # ...  end    class Picture < ApplicationRecord    belongs_to :imageable, polymorphic: true    # ...  end  

What I want to do is to allow a User to set a profile picture from the images associated with it, so I can call @user.profile_picture on a User object and retrieve the profile picture.

How to create multiple submit buttons with different formats in a form

Posted: 22 Nov 2016 03:35 AM PST

Hi I'm working on a project in which I have a form which consists of a list of posts each with a checkbox and two submit buttons. One submit button is view, which takes the user to a template containing all the posts checked. The other is a delete button, which should keep the user on the page, delete the posts and refresh the list.

The problem is that I need to be able to change the submit format depending on which button the user pushes, HTML for view and js for delete.

Originally I had:

<%= form_tag multi_posts_path(format: :html) do %>      #checkboxes      <%= button_tag('View Checked', name: 'commit', value: 'view') %>  <% end %>  

for just viewing, but obviously that wont work for deleting and I'm not sure how to change it to work.

Any help would be great!

Rails rails-money undefined method `cents'

Posted: 22 Nov 2016 02:26 AM PST

I am attempting to implement money-rails and I have run into the following error:

undefined method `cents' for "1,000.00":String

I followed this tutorial to get a "fancy" currency input field.

DB schema:

t.integer  "balance_cents",    default: 0,     null: false  t.string   "balance_currency", default: "USD", null: false  

Model:

monetize :balance_cents, as: :balance, allow_nil: :true, :numericality => { :greater_than_or_equal_to => 0}    def initialize(attributes = {})    super    @balance = attributes[:balance]  end  

Form:

<%= form_for(@asset, url: assets_new_path) do |f| %>    <%= f.label :balance, "Balance / Value ($)" %>    <%= f.number_field :balance, data: { role: 'money', a_sep: ',', a_dec: '.' }, class: 'form-control' %>  

Controller:

def create    @asset = Asset.new(asset_params)    if @asset.save      flash[:success] = "New asset created successfully."      redirect_to assets_path    else      ...    end  end    def asset_params    params.require(:asset).permit(:balance)  end  

Should I be setting up the :balance input field another (better) way?

Rails 4 - Combining scopes in a DRY manner

Posted: 22 Nov 2016 04:27 AM PST

Lets say I have this 3 scopes:

scope :assembly_reclamation, -> { where(status: 5) }  scope :customer_reclamation, -> { where(status: 9) }  scope :wrong_delivery,       -> { where(status: 12) }  

Now let's say that I want to make a scope that joins those 3 categories. I am doing it right now like this:

scope :returnable, -> { where(status: [5, 9, 12]) }  

While this works, it has some disadvantages. if I were to change the conditions of one of the 3 categories, I would have to rework the scope that contains them all as well.

Something like this seems more DRY:

scope :returnable, -> { assembly_reclamation.or.customer_reclamation.or.wrong_delivery }  

But this is not valid code.

Is there a way to code it in such a fashion?

UPDATE

I know I have used an example using categories and ids, but please do not make it about it. It is about merging scopes.

UPDATE 2 I have changed the name of the attributes from idto status, because everyone was concentrating on the issue of the id, and that is not the point of the question

Does sidekiq use any dependent application to initialise its processes?

Posted: 22 Nov 2016 02:28 AM PST

I am trying to understand how sidekiq works.

Does sidekiq load all the dependencies via the rails initializer by loading all the gems or does it use some sort of an applications server while spawning its workers?

No comments:

Post a Comment