Sunday, November 13, 2016

Display last body message on messaging system from scratch | Fixed issues

Display last body message on messaging system from scratch | Fixed issues


Display last body message on messaging system from scratch

Posted: 13 Nov 2016 07:26 AM PST

I made a messaging system from scractch on my App. All works good but i just want to customize more. So I want to display the last message for each Conversation by user_id inbox in my view . I have 2 models : Conversation and Message.

I can display only this

I m lost. Can you help me ?

messages_controller.rb

class MessagesController < ApplicationController   before_action :authenticate_user!    before_action do     @conversation = Conversation.find(params[:conversation_id])    end  def index     @messages = @conversation.messages    if @messages.length > 10     @over_ten = true     @messages = @messages[-10..-1]    end    if params[:m]     @over_ten = false     @messages = @conversation.messages    end   if @messages.last    if @messages.last.user_id != current_user.id     @messages.last.read = true;    end   end  @message = @conversation.messages.new   end  def new   @message = @conversation.messages.new  end  def create   @message = @conversation.messages.new(message_params)   if @message.save          usercourant = User.find(current_user.id)   (@conversation.users.uniq - [usercourant]).each do |user|     # user = User.find(user.id)    # users = User.find(current_user.id)    Notification.create(recipient: user, actor: current_user, action: "a répondu", notifiable: @conversation)   end      SendMessageMailer.new_message(@message).deliver_later    redirect_to conversation_messages_path(@conversation)   end  end  private   def message_params    params.require(:message).permit(:body, :user_id)   end  end  

Conversations_controller.rb

class ConversationsController < ApplicationController    before_action :authenticate_user!      # GET /conversations    # GET /conversations.json    def index      @users = User.all      @camping = Camping.all        # Restrict to conversations with at least one message and sort by last updated      @conversations = Conversation.joins(:messages).distinct              end      # POST /conversations    # POST /conversations.json    def create    if Conversation.between(params[:conversation][:sender_id], params[:conversation][:recipient_id]).present?      @conversation = Conversation.between(params[:conversation][:sender_id], params[:conversation][:recipient_id]).first            else      @conversation = Conversation.create!(conversation_params)    end      redirect_to conversation_messages_path(@conversation)  end      private      # Use callbacks to share common setup or constraints between actions.      def conversation_params        params.require(:conversation).permit(:sender_id, :recipient_id, :user_id)      end  end  

conversation.rb

class Conversation < ActiveRecord::Base   belongs_to :sender, :foreign_key => :sender_id, class_name: 'User'   belongs_to :recipient, :foreign_key => :recipient_id, class_name: 'User'     belongs_to :user    has_many :users, through: :messages      has_many :messages, dependent: :destroy        validates_uniqueness_of :sender_id, :scope => :recipient_id  scope :between, -> (sender_id,recipient_id) do   where("(conversations.sender_id = ? AND conversations.recipient_id =?) OR (conversations.sender_id = ? AND conversations.recipient_id =?)", sender_id,recipient_id, recipient_id, sender_id)   end     def message_time    created_at.strftime("%m/%d/%y at %l:%M %p")   end    end  

message.rb

class Message < ActiveRecord::Base   belongs_to :conversation   belongs_to :user     validates_presence_of :body, :conversation_id, :user_id   def message_time    created_at.strftime("%m/%d/%y at %l:%M %p")   end  end  

/messages/index.html.erb

<div class="container">  <h1>Conversation</h1>    <% if @over_ten %>   <%= link_to 'Show Previous', "?m=all" %>  <% end %>    <div class="ui segment">   <% @messages.each do |message| %>    <% if message.body %>       <% user = User.find(message.user_id) %>       <li class="messaging">        <div class="imageavatarmessage"><%= image_tag user.avatar(:thumb), class:"imageavatarmessage" %></div>        <div class="messagingprenom"><%= user.prenom %></div>        <%= message.message_time %>        <div class="list">           <%= message.body %>            <% end %>           <% end %>      </div>  </li>  </div>    <%= form_for [@conversation, @message], html: {class: "ui reply form"} do |f| %>   <div class="field">     <%= f.text_area :body, class: "form-control" %>   </div>   <%= f.text_field :user_id, value: current_user.id, type: "hidden" %>     <%= f.submit "Add Reply", class: "ui blue labeled submit icon button" %>  <% end %>  </div>  

/conversations/index.html.erb

<div class="ui segment">   <h3>Boite de réception</h3>   <div class="ui list">    <div class="item">     <% @conversations.each do |conversation| %>     <% if conversation.sender_id == current_user.id || conversation.recipient_id == current_user.id %>      <% if conversation.sender_id == current_user.id %>        <% recipient = User.find(conversation.recipient_id) %>        <% else %>        <% recipient = User.find(conversation.sender_id) %>        <% end %>      <div class="col-md-12">      <div class="col-md-2">      <p>Conversation avec <%= link_to recipient.prenom, conversation_messages_path(conversation)%></p>      <p><%= image_tag recipient.avatar(:small), class:"imageavatarmessage" %></p>      </div>        <div class="col-md-8">       <%= @conversations.last %>        </div>        <div class="col-md-2">      <p>Il y a <%= time_ago_in_words(conversation.updated_at)%></p>      </div>      </div>       <% end %>    <% end %>    </div>   </div>  </div>  

I want to display only the last one message for each conversations in my /conversations/index.html.erb I tested this <%= @conversations.last %> but it doesn't work...

Can you help me ?

Not receiving Incoming Email to rails application using mailgun

Posted: 13 Nov 2016 07:37 AM PST

My application runs on GoDaddy DNS I'm using mailing service with Google Apps Now I need to use Mailgun for specific functionalities in my application (for sending and receiving mails to application for the users. I have followed instructions and added all DNS records under Domain Tab in Mailgun in my GoDaddy GoDaddy MX Settings.

But for the last section under Optional DNS Records (which they say need to be added for incoming mails) I still see that "We couldn't find this record when we checked your DNS records. This is only required if you want to use our inbound routes feature."Mailgun Domain Tab. I have reached out to GoDaddy and they confirm to me that my DNS MX are correctly propagated. I do not have any conflict. And Mailgun MX records are correctly added as subdomain.

I need help in figuring this out. As of now I'm not able to receive incoming emails to my application using Mailgun (But I was successfully able to test route and email under Route tab in Mailgun). Any ideas what could be wrong ?

;

Deserializing data from Rails API to Angular 2 models

Posted: 13 Nov 2016 07:24 AM PST

I'm trying to call a Rails backend API and return some simple data - an array of models. For example, I have a car model, that has properties for make, year and price.

The Angular 2 model is similarly defined.

When making the http get call to the Rails app:

class CarsController < ApplicationController      respond_to :json        def index          respond_with Car.all.order(:make)      end  end  

the rails app will return the data as a jSON array of objects that are each wrapped in an object:

[ { car: { year: 2017, Make: Honda, Model: Accord } },     { car: { year: 2010, Make: Toyota, Model: Solara } }  ]  

etc

The Angular2 routine to call for, and convert the returned data:

  getCars(): Observable<Car[]> {      return this.http.get(this.url)                      .map(this.extractData)                          .catch((res: Response ) => this.handleError(res));    }      private extractData(res: Response) {      let body = res.json();      return body || { };    }  

does not work - it returns an empty object, as it expects the data to not have each object enclosed within another object.

How do I get Angular2 to do the right thing? How can I convert the returned data so Angular2 will populate my array of Cars correctly?

(I can't believe I can't find any reference to this issue when searching!)

Thanks.

Redirect back with errors

Posted: 13 Nov 2016 07:17 AM PST

I have a controller:

controller/streets_controller.rb

class StreetsController < ApplicationController    before_action :set_street, only: [:show, :edit, :update, :destroy]      def show      @house = @street.houses.build    end      .......  

And a view for that show action. There I also display a form to create new street houses:

views/streets/show.html.erb

<h1>Street</h1>  <p>@street.name</p>    <%= render '/houses/form', house: @house %>  

When somebody submits the houses/form the request goes to the houses_controller.rb

class HousesController < ApplicationController      def create      @house = House.new(house_params)        respond_to do |format|        if @house.save          format.html { redirect_back(fallback_location: streets_path) }          format.json { render :show, status: :created, location: @house }        else          format.html { redirect_back(fallback_location: streets_path) }          format.json { render json: @house.errors, status: :unprocessable_entity }        end      end    end  

So far it works that when somebody inserts correct house_params it redirects back and creates the house correctly

But when somebody inserts wrong house_params it redirects_back but it doesn't show the house errors in the form, it shows the form for a new house @house = @street.houses.build

How can I redirect to the StreetsController with the @house object, so that the errors are shown and also the house form is filled?

Thanks

Rails same app with different databases

Posted: 13 Nov 2016 06:22 AM PST

I'm building a report app in Rails for a current desktop app. The app is kind of pos/accounting.

So at the moment there are different clients with the desktop app installed at shop or office. Each one has its own mysql database.

I am now planning how to setup the server, most probably heroku.

Given that I will keep the databases for each client separated, I'm trying to understand the best path to follow.

Another thing to consider is that there will be different version of the app, i.e. restaurant, bar, shop etc.. Different versions will use the same database. I'll just need to change some controller and view. Most probably I'll handle this using namespace.

For a client(company) multiple users will have access to the app.

The solution I thought is to create a database table company and add a column company to users table.

Things that could change from a client to another:

  • call different images from assets such as logo
  • there might be custom views or even controller if a client requests some customization
  • use different database
  • domain possibly, but that's not that important wouldn't a be a big deal to use the same

Then based on user.company show a different logo or any other required image, render a view instead of another, at login connect to the proper database.

I don't know yet how to implement it, right now I'm still evaluating the best approach to follow. But this way maintenance/updates would be easy to manage even if maybe performance will be a bit lower and code harder to understand with possible customizations all together but that's acceptable.

Is this a reasonable solution or should I consider something different? Am I missing something important to consider?

Dynamic select tag in Ruby on Rails

Posted: 13 Nov 2016 06:24 AM PST

I am a newbie to Ruby on Rails . I have started working in RoR month ago. My question is:

How can I make dynamic select tag that shows me sizes based on selected color of the product variant via AJAX?

Each product has many variants. Each variant has one color, one size and quantity.

Here are my models:

class Color < ActiveRecord::Base      has_many :variants, dependent: :destroy      validates :name, presence: true, length: {minimum: 2, maximum: 20}      validates :hex, presence: true, uniqueness: true, length: { is: 7}, format: { with: /\A#([A-Fa-f0-9]{6}|[A-Fa-f0-9]{3})\z/ }  end    class Size < ActiveRecord::Base      has_many :variants, dependent: :destroy      validates :size,  uniqueness:  true, numericality: { only_integer: true, greater_than_or_equal_to: 28, less_than_or_equal_to: 49}  end    class Variant < ActiveRecord::Base      belongs_to :product      belongs_to :size      belongs_to :color        validates :quantity, :numericality => { :greater_than_or_equal_to => 0 }      validates :color_id, presence: true      validates :size_id, presence: true  end  

Here is my product view:

<%= form_tag({controller: "carts", action: "add"}, method: "post", class: "form") do %>      Color:       <%= select_tag :color, options_from_collection_for_select(@colors, "name", "name"), id: 'color', prompt: 'Select color',  onchange: 'onChange()' %>       Quantity:       <%= number_field_tag :quantity, '1', min: 1%>       Size:       <%= select_tag :size, options_from_collection_for_select(@sizes,"size", "size"), id: 'size', prompt: 'Select size', onchange: 'onChange()'%>        <%= submit_tag "ADD TO CART", class: 'btn btn-default' %>      <%= submit_tag "BUY NOW", class: 'btn btn-dark-grey', style: "margin-left:10px"%>  <% end %>  

I will provide more information if it is needed. Thanks in advance.

how to Making a perticuler column(td) into a link in a Rails

Posted: 13 Nov 2016 05:44 AM PST

I want to create clickable column of a Datatable ...i am also need to redirect show page only the particular two column click.

I am also tried the following code ..

 $("#sentmailTable tbody").on('click', 'td', function () {    if ($(this).index() == 5 ) {             return;        }      });  

but its not working .can any one solve this?

Working in rails console but getting : "NoMethodError in Workouts#index (undefined method `movements' for nil:NilClass)"

Posted: 13 Nov 2016 07:24 AM PST

I've been searching these forums for the passed 2 days and finally given up. I've been working on a rails app where you can upload workouts, and then have other view them and download any attached excel files. My form looks like this

  '<div class="form-group">       <div class="control-label col-md-2">                  <%= f.label :name, "Workout name" %><br>                </div>                <div class="col-md-10">                  <%= f.text_field :name, class: "form-control" %>                </div>              </div>              <div class="form-group">                <div class="control-label col-md-2">                  <%= f.label :summary, "Summary", placeholder: "Who's this for? what experience level? Athletes or Bodybuilders etc"  %>                </div>                <div class="col-md-10">                  <%= f.text_area :summary, class: "form-control", rows: 10%>                </div>              </div>            <div class="clearfix">              <div class="col-lg-3 col-md-6">              <%= f.label :Movement %>                <%= f.fields_for :movements do |movement| %>                  <%= render 'movement_fields', f: movement %>              <% end %>                  <div class="links">                    <%= link_to_add_association 'Add movement', f, :movements, class: "pull-right d-inline-block btn btn-primary add-button" %>                    </br>                    </br>                  </div>              </div>              <div class="col-lg-3 col-md-6">                   <%= f.label :Reps %>                      <%= f.fields_for :reps do |rep| %>                        <%= render 'rep_fields', f: rep %>                      <% end %>                  <div class="links">                    <%= link_to_add_association 'Add Reps', f, :reps, class: "pull-right d-inline-block btn btn-primary add-button" %>                  </br>                  </br>                  </div>              </div>              <div class="col-lg-3 col-md-6">              <%= f.label :Sets %>                      <%= f.fields_for :zets do |zet| %>                        <%= render 'zet_fields', f: zet %>                      <% end %>                  <div class="links">                    <%= link_to_add_association 'Add Set', f, :zets, class: "pull-right d-inline-block btn btn-primary add-button" %>                  </div>                    </br>                    </br>              </div>              <div class="col-lg-3 col-md-6">                   <%= f.label :Weights %>                      <%= f.fields_for :weights do |weight| %>                        <%= render 'weight_fields', f: weight %>                      <% end %>                  <div class="links">                    <%= link_to_add_association 'Add weight', f, :weights, class: "pull-right d-inline-block btn btn-primary add-button" %>                  </div>                    </br>                    </br>               </div>              <strong>Upload image: </strong>                  <span class="picture">                      <%= f.file_field :attachment %>                  </span>            </div>                <div class="form-group">                <div class="col-md-offset-2 col-md-10">                  <%= f.submit class: "btn btn-success btn-lg" %>                </div>              </div>            <% end %>          </div>        </div>      </div>`  

Which seems to upload everything i need to the database, because when i go through the entries it seems to have the data i need i.e workout_id attached to a movement etc.

Heres the schema.rb

# Deleted some other columns in this that are in the app that aren't relevant to the post to reduce the amount of text. Exercises column is from another element in the app that works that i used basically the exact same method in creating.     ActiveRecord::Schema.define(version: 20161113011850) do        create_table "exercises", force: :cascade do |t|      t.integer  "duration_in_min"      t.text     "workout"      t.date     "workout_date"      t.integer  "user_id"      t.datetime "created_at",      null: false      t.datetime "updated_at",      null: false    end      add_index "exercises", ["user_id"], name: "index_exercises_on_user_id"      create_table "movements", force: :cascade do |t|      t.string   "name"      t.integer  "exercise_id"      t.integer  "workout_id"      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false      t.integer  "workout_id"    end      add_index "movements", ["exercise_id"], name: "index_movements_on_exercise_id"    add_index "movements", ["workout_id"], name: "index_movements_on_workout_id"        create_table "reps", force: :cascade do |t|      t.integer  "amount"      t.integer  "exercise_id"      t.integer  "workout_id"      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false    end      add_index "reps", ["exercise_id"], name: "index_reps_on_exercise_id"    add_index "reps", ["workout_id"], name: "index_reps_on_workout_id"      create_table "reviews", force: :cascade do |t|      t.text     "body"      t.integer  "user_id"      t.integer  "recipe_id"      t.datetime "created_at"      t.datetime "updated_at"    end      create_table "users", force: :cascade do |t|      t.string   "username"      t.string   "email",                  default: "",    null: false      t.string   "encrypted_password",     default: "",    null: false      t.string   "reset_password_token"      t.datetime "reset_password_sent_at"      t.datetime "remember_created_at"      t.integer  "sign_in_count",          default: 0,     null: false      t.datetime "current_sign_in_at"      t.datetime "last_sign_in_at"      t.string   "current_sign_in_ip"      t.string   "last_sign_in_ip"      t.datetime "created_at",                             null: false      t.datetime "updated_at",                             null: false      t.string   "first_name"      t.string   "last_name"      t.boolean  "admin",                  default: false    end      add_index "users", ["email"], name: "index_users_on_email", unique: true    add_index "users", ["reset_password_token"], name: "index_users_on_reset_password_token", unique: true      create_table "weights", force: :cascade do |t|      t.integer  "kilogram"      t.integer  "workout_id"      t.integer  "exercise_id"      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false    end      add_index "weights", ["exercise_id"], name: "index_weights_on_exercise_id"    add_index "weights", ["workout_id"], name: "index_weights_on_workout_id"      create_table "workouts", force: :cascade do |t|      t.string   "name"      t.text     "summary"      t.integer  "user_id"      t.string   "attachment"      t.datetime "created_at",      null: false      t.datetime "updated_at",      null: false      t.integer  "duration_in_min"    end      create_table "zets", force: :cascade do |t|      t.integer  "quantity"      t.integer  "exercise_id"      t.integer  "workout_id"      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false    end      add_index "zets", ["exercise_id"], name: "index_zets_on_exercise_id"    add_index "zets", ["workout_id"], name: "index_zets_on_workout_id"    end  

And the model workout.rb

class Workout < ActiveRecord::Base belongs_to :user mount_uploader :attachment, AttachmentUploader

  has_many :movements    has_many :reps    has_many :zets    has_many :weights        accepts_nested_attributes_for :movements,                                                              reject_if: proc { |attributes| attributes['name'].blank? },                                                              allow_destroy: true      accepts_nested_attributes_for :reps,                                                              reject_if: proc { |attributes| attributes['amount'].blank? },                                                              allow_destroy: true    accepts_nested_attributes_for :zets,                                                              reject_if: proc { |attributes| attributes['quantity'].blank? },                                                              allow_destroy: true      accepts_nested_attributes_for :weights,                                                              reject_if: proc { |attributes| attributes['kilogram'].blank? },                                                              allow_destroy: true      validates :name, presence: true    validates :summary, presence: true    validates :movements, presence: true    validates :reps, presence: true    validates :zets, presence: true    validates :weights, presence: true  end  

and the controller workouts_controller.rb

 class WorkoutsController < ApplicationController        before_action :set_workout, only: [:edit, :update, :show, :like, :review]        before_action :authenticate_user!, except: [:show, :index, :like, :search]        before_action :require_same_user, only: [:edit, :update]        before_action :admin_user, only: :destroy      def index      @workouts = Workout.all    end      def show      @random_workout = Workout.where.not(id: @workout).order("RANDOM()").first(3)    end      def new      @workout = Workout.new    end      def create      @workout = Workout.new(workout_params)      @workout.user = current_user        if @workout.save        flash[:success] = "Your workout was created successfully!"        redirect_to workouts_path      else        render :new      end    end      def edit      end      def update      if @workout.update(workout_params)        flash[:success] = "Your workout was update success"        redirect_to workout_path(@workout)      else        render :edit      end    end      def destroy      Workout.find(params[:id]).destroy      flash[:success] = "Workout Deleted"      redirect_to workouts_path    end      def review      review = Review.create(body: params[:body], user: current_user, workout: @workout)      if review.valid?        flash[:success] = "Thank you for reviewing this workout"      else        flash[:danger] = "Review failed to post"      end      redirect_to :back    end      def deletereview      Review.find(params[:revid]).destroy      flash[:success] = "Review deleted"      redirect_to :back    end      private        def workout_params          params.require(:workout).permit(:name, :summary, :attachment, :user_id, movements_attributes: [:id, :name, :_destroy], reps_attributes: [:id, :amount, :_destroy], zets_attributes: [:id, :quantity, :_destroy], weights_attributes: [:id, :kilogram, :_destroy],)      end        def set_workout        @workout = Workout.find(params[:id])      end        def require_same_user        if current_user != @recipe.user and !current_user.admin?          flash[:danger] = "You can only edit your own recipes"          redirect_to recipes_path        end      end          def admin_user        redirect_to recipes_path unless current_user.admin?      end    end  

and finally the index.html.erb

<h1>Listing Workouts</h1>    <table class="table table-hover table-responsive">    <thead>      <tr>        <th>Name</th>        <th>Summary</th>        <th>Attachment</th>        <th>Exercises</th>        <th colspan="3"></th>      </tr>    </thead>      <tbody>      <% @workouts.each do |workout| %>        <tr>          <td><%= workout.name %></td>          <td><%= truncate(workout.summary, length: 350) %><%= link_to 'click to see workout', workout_path(workout)%></td>          <td><%= link_to "Download Workout", workout.attachment_url %>%></td>          <td><%= link_to 'Show', workout %></td>      <% end %>      <% @workout.movements.each do |movement| %>          <td>            <ol>              <li>                <%= movement.name %>              </li>            </ol>      <%end%>      <% @workout.reps.each do |rep| %>          <td>            <ol>              <li>                <%= rep.amount %>              </li>            </ol>      <%end%>      <% @workout.zets.each do |zet| %>          <td>            <ol>              <li>                <%= zet.quantity %>              </li>            </ol>      <%end%>      <% @workout.weights.each do |weight| %>          <td>            <ol>              <li>                <%= weight.kilogram %>              </li>            </ol>      <%end%>          </td>        </tr>    </tbody>  </table>    <br>    <%= link_to 'New Workout', new_workout_path %>  

Sorry about all the text, i just wanted to include everything the first time round. And i know this question has been asked to death and i appologise, for not being able to workout the issue from the already answered questions, but, was reallly hoping to figure out why im getting this error.

NoMethodError in Workouts#index Showing /home/ubuntu/workspace/app/views/workouts/index.html.erb where line #24 raised:

undefined method `movements' for nil:NilClass

As I mentioned I've implemented almost the exact same functionality twice now, on 2 other functions within the app, which work almost exactly the same as this is 'supposed to'. So im quite confused :(

Rails & Google API - API calls with an existing access_token

Posted: 13 Nov 2016 05:23 AM PST

Using the https://github.com/google/google-api-ruby-client library, how to make calls with an already taken access_token.

I think I need to create an Authorization object with only the access_token.

Rails FactoryGirl - How to invoke a method in an associated factory object?

Posted: 13 Nov 2016 05:21 AM PST

Given an order object in a webshop that normally updates its total price each time a booking (a product_order jointable object) is made, how would I make this happen in FactoryGirl.

I was simply thinking something like this, where order.sum_all_bookings does the updating of the order object:

FactoryGirl.define do    factory :booking do      product_name 'Honeyjar 400 ml'      product_quantity '1'      product_price '3,99'      order        after(:create) do |booking|        booking.order.sum_all_bookings      end    end  end

Unfortunately nothing changes in the order object.

Pagnation in bootstrap nav tabs using kamanari on rails

Posted: 13 Nov 2016 05:09 AM PST

In my controller

if params[:topic].nil?        if user_signed_in?          @questions = Question.where(:id => current_user.following).order('created_at DESC').page(params[:question_followed]).per(1)          @questionasked = Question.where(:user_id => current_user.id).order('created_at DESC').page(params[:question_asked]).per(1)          @questionans = Question.where(:id => Answer.where(:user_id => current_user.id).map {|a| a.question_id}).order('created_at DESC').page(params[:question_ans]).per(1)        else          @questions = Question.all.order('created_at DESC').page(params[:page]).per(1)        end      end  

and in the views

<div class="nav-tabs-custom cause-block" >        <ul class="nav nav-tabs" id="myTab">          <li class="active"><a href="#menu1" data-toggle="tab">Following</a></li>          <li><a href="#menu2" data-toggle="tab">Asked</a></li>          <li><a href="#menu3" data-toggle="tab">Answered</a></li>        </ul>      </div>        <div class="tab-content">          <div id="menu1" class="tab-pane fade in active">            <div class="row">              <div class="col-md-8">                <% @questions.each do |question| %>                  <%= render 'question', :question => question, :answers => question.answers.order('created_at DESC'), :full => false %>                <% end %>                   <!--/.box -->              </div>            </div>            <%= paginate @questions, param_name: "question_followed"%>          </div>          <div id="menu2" class="tab-pane fade">            <!-- for the contests -->            <div class="row">              <div class="col-md-8">                <% if !@questionasked.nil?%>                  <% @questionasked.each do |question| %>                    <%= render 'question', :question => question, :answers => question.answers.order('created_at DESC'), :full => false %>                  <% end %>                 <!--/.box -->              </div>            </div>            <%= paginate @questionasked,param_name: "question_asked"%>            <%end%>          </div>          <div id="menu3" class="tab-pane fade">            <!--for causes  -->            <!-- user block -->            <div class="row">              <div class="col-md-8">                <% if !@questionans.nil?%>                  <%  @questionans.each do |question| %>                    <%= render 'question', :question=> question, :answers => question.answers.order('created_at DESC'), :full => false %>                  <% end %>                 <!--/.box -->              </div>            </div>            <%= paginate @questionans, param_name: "question_ans"%>            <%end%>          </div>        </div  

Now what this code is doing it is loads the last question of asked, following and answered and when I click page 1 in pagination bar, it takes me back to the same question(last one) rather it should load the first question from the followed , answered and asked part and on thing more when i click pagination buttons it makes url /?question_ans=2&type=following and then it changes to /questions which is default one that i have provided in the routes.Kindly giude me on how can i fix this.

Creating a nested object from another controller gives error "couldn't find Object id = X" Rails

Posted: 13 Nov 2016 05:01 AM PST

I would like the promoter to create a nested object (referree) in his Show. Everything is set but it is - obviously not working. When submitting the form in Promoter / Show to create a Referee I have this error : "Couldn't find Referree with 'id'=1 " What is wrong ? It is very important to create the form in this view and not another. How can I do ?

Thanks

My models :

class Promoter < ApplicationRecord   has_many :referrees, dependent: :destroy  end    class Referree < ApplicationRecord   belongs_to :promoter  end  

First controller Promoters :

class PromotersController < ApplicationController    before_action :find_promoter      def show      @referree = Referree.new    end      def new    end      def create      @promoter = Promoter.new(promoter_params)      @promoter.save    end      private      def promoter_params      params.require(:promoter).permit(:firstname, :lastname, :email)    end      def find_promoter      @promoter = Promoter.find(params[:id])    end    end  

Second controller Referrees :

class ReferreesController < ApplicationController    before_action :find_referree, only: [ :new, :create ]      def new      @referree = Referree.new    end      def show      @referree = Referree.new    end      def create      @referree = @promoter.referrees.build(referree_params)      @referree.save    end      private      def referree_params      params.require(:referree).permit(:email)    end      def find_referree      @referree = Referree.find(params[:promoter_id])    end  end  

Form in Promoter/Show view:

<%= simple_form_for [@promoter, @referree] do |f| %>    <%= f.input :email %>    <%= f.submit "add a referree", class: "btn btn-primary" %>  <% end %>  

When is executed the code defined in the class section of the model

Posted: 13 Nov 2016 05:13 AM PST

If I put this in my model:

class Sample < ApplicationRecord    enum level: [:one, :two, :three].map{|e| [e,e]}.to_h  

This section

[:one, :two, :three].map{|e| [e,e]}.to_h  

Will be executed only once? when the model is first loaded? or it will be executed multiple times?

Alternatives to convert a array to a hash using same keys and values

Posted: 13 Nov 2016 04:52 AM PST

I want to convert:

[:one, :two, :three]  

to:

{one: :one, two: :two, three: three}  

So far I'm using this:

Hash[[:basic, :silver, :gold, :platinum].map { |e| [e, e] }]  

But I would like to know if it's possible by some other way?

This is to use in a Rails enum definition in model, to save values as strings in db.

Why I obtain this error message installing the Ruby bundler gem "ERROR: Failed to build gem native extension"?

Posted: 13 Nov 2016 05:15 AM PST

I am not so into Linux and Ruby and I am having some problem trying to install Redmine on an Ubuntu 16.04 system.

I am following this official guide: http://www.redmine.org/projects/redmine/wiki/HowTo_Install_Redmine_on_Ubuntu_step_by_step

I am finding some problem when I perform this command:

sudo gem update  

because during its execution I am obtaining many error messages like this:

Updating ffi  Fetching: ffi-1.9.14.gem (100%)  Building native extensions.  This could take a while...  ERROR:  Error installing ffi:          ERROR: Failed to build gem native extension.        current directory: /var/lib/gems/2.3.0/gems/ffi-1.9.14/ext/ffi_c  /usr/bin/ruby2.3 -r ./siteconf20161113-6502-1eskdz9.rb extconf.rb  mkmf.rb can't find header files for ruby at /usr/lib/ruby/include/ruby.h    extconf failed, exit code 1  

Why? What could be the problem? What am I missing? How can I fix this issue?

I am not into Ruby, what exactly is this "bundler gem" of Ruby?

Tnx

Rails 4: Multi-level joins with ActiveRecord

Posted: 13 Nov 2016 03:16 AM PST

I am adding another layer of complexity to my data model. Previously: A Country had many Stores, which in turn had many Products.

I am now introducing Cities so that: A Country has many Cities which have many Stores which have many Products.

The data I work with contains Stores that may not have Products (yet), Cities that may not have Stores (yet) and Countries that may not have Cities (yet).

I want to query all Countries in which to find Products. (I.e. so I can fill a landing page with all Countries where it makes sense for a user to look for stuff.)

Previously (with Country > Store > Product), I used this, and it worked well:

Country.joins(:stores => :products).group("countries.id").having("count(products.id)>0")  

But I cannot get my head around this additional layer (Country > City > Store > Product). For instance, this doesn't work:

Country.joins(:cities => :stores).joins(:stores => :products).group("countries.id").having("count(products.id)>0")  

...yielding this error:

ActiveRecord::ConfigurationError: Association named 'stores' was not found on Country  

Can anyone help?

(I am trying to be as SQL-agnostic as possible, so if it can be done with ActiveRecord methods I would like to do it that way.)

Rails show maximum amount of a Bid for every id product

Posted: 13 Nov 2016 06:25 AM PST

I'm trying to print out in the index view page next to every product the maximum amount of the bid for that product. So the outcome should be like this in the index view:

Banana (maximum amount for banana)
Table (maximum amount for table)
etc

I Know how to print out the maximum of the total of all products, but not the maximum amount of each product. That being said I attach my code:

ROUTES:

Rails.application.routes.draw do    # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html      get "/new", to: "users#new"    # get "/index", to: "products#index"    get "/products", to: "products#index", as: :products      get "/new_products", to: "products#new"    #  el form_for siempre necesitará un path en forma de as: ... ya que no le sirve solo la url    post "/products", to: "products#create"    get "/products/show/:id", to: "products#show", as: :product    post "/bids/new_bid", to: "bids#create"    # post "/new_bid", to: "bids#create"    post "/products", to: "bids#pass_bid_amount"    end

Bids controller:

class BidsController < ApplicationController        def create      user= User.find_by(email: params[:email])      if Time.now < params[:product_deadline]        @bid= Bid.new(amount: params[:amount].to_i, user_id: user.id.to_i, product_id: params[:product_id].to_i)				        if @bid.save          redirect_to product_path(@bid.product_id)        else          render plain: "something went wrong"        end      else        render plain:" Too late"      end	    end      def pass_bid_amount      @bid= Bid.new(amount: params[:amount].to_i, user_id: user.id.to_i, product_id: params[:product_id].to_i)      @bid.save      render "index"      # redirect_to products_path(@bid.product_id)		    end    end

INDEX.HTML.ERB:

<% @products.each do |product| %>    <p><%= link_to product.title, product_path(product.id) %></p>    <p><% %></p>   <% end %>      <p><%=  Bid.maximum(:amount) %> </p>    This maximum amount is not of every single object but the total of all products    <p><%= @products.inspect %></p>  <p><%= Bid.new.inspect %></p>  <!-- <p><%= @bid.inspect %></p> -->

And what I see in the Browser is this:

banana    table    tree    99999999    This maximum amount is not of every single object but the total of all objects    #<ActiveRecord::Relation [#<Product id: 1, title: "banana", description: "this is a fruit", user_id: nil, deadline: "2016-11-22 00:00:00", created_at: "2016-11-12 12:40:01", updated_at: "2016-11-12 12:40:01">, #<Product id: 2, title: "table", description: "this is an object", user_id: nil, deadline: "2016-11-22 00:00:00", created_at: "2016-11-12 12:40:01", updated_at: "2016-11-12 12:40:01">, #<Product id: 3, title: "tree", description: "this is a tree", user_id: nil, deadline: "2016-11-22 00:00:00", created_at: "2016-11-12 12:40:01", updated_at: "2016-11-12 12:40:01">]>    #<Bid id: nil, amount: nil, user_id: nil, product_id: nil, created_at: nil, updated_at: nil>

SCHEMA:

ActiveRecord::Schema.define(version: 20161109151534) do      create_table "bids", force: :cascade do |t|      t.integer  "amount"      t.integer  "user_id"      t.integer  "product_id"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false      t.index ["product_id"], name: "index_bids_on_product_id"      t.index ["user_id"], name: "index_bids_on_user_id"    end      create_table "products", force: :cascade do |t|      t.string   "title"      t.string   "description"      t.integer  "user_id"      t.datetime "deadline"      t.datetime "created_at",  null: false      t.datetime "updated_at",  null: false      t.index ["user_id"], name: "index_products_on_user_id"    end      create_table "users", force: :cascade do |t|      t.string   "email"      t.string   "name"      t.datetime "created_at", null: false      t.datetime "updated_at", null: false    end    end

blog post issue in Comments

Posted: 13 Nov 2016 03:45 AM PST

I am following the guide http://guides.rubyonrails.org/getting_started.html but I have an issue.

As u can see in image, below Comments section some irrelevant information is presenting, what is it and how to avoid it from displaying. it will be helpful if some expert just sort it out i am new to rails........

enter image description here

Rails, Amazon S3 storage, CarrierWave-Direct and delayed_job - is this right?

Posted: 13 Nov 2016 02:21 AM PST

I've just discovered that Heroku doesn't have long-term file storage so I need to move to using S3 or similar. A lot of new bits and pieces to get my head around so have I understood how direct upload to S3 using CarrierWave-direct and then processing by delayed_job should work with my Rails app?

What I think should happen if I code this correctly is the following:

  1. I sign up to an S3 account, set-up my bucket(s) and get the authentication details etc that I will need to program in (suitably hidden from my users)
  2. I make sure that direct upload white lists don't stop cross-domain from preventing my uploads (and later downloads)
  3. I use CarrierWave & CarrierWave-direct (or similar) to create my uploads to avoid loading up my app during uploads
  4. S3 will create random access ('filename') information so I don't need to worry about multiple users uploading files with the same name and the files getting overwritten; if I care about the original names I can use metadata to store them.
  5. CarrierWave-direct redirects the users browser to an 'upload completed' URL after the upload from where I can either create the delayed_job or popup the 'sorry, it went wrong' notification.
  6. At this point the user knows that the job will be attempted and they move on to other stuff.
  7. My delayed_job task accesses the file using the S3 APIs and can delete the input file when completed.
  8. delayed_job completes and notifies the user in the usual way e.g. an e-mail.

Is that it or am I missing something? Thanks.

How to save google.maps.Data.MultiPolygon to geometry datatype column in postgres database in rails?

Posted: 13 Nov 2016 02:27 AM PST

I am a beginner in rails framework, so please pardon my naive question. I have a google.maps.Data.MultiPolygon object on my frontend which I want to save in my database. The table searches creates a new entry everytime a user searches, contains different columns out of which I have added another column with datatype :geometry, which will be updated when the user draws a polygon at a specific search. So we need to update a search entry in the database, for which I am using put call. I cannot send the whole google.maps.Data.MultiPolygons object on the put call, since $.params() is unable to serialise the object (this problem is the same which is faced here).

var polygons = new google.maps.Data.MultiPolygon([polygon]);  var search_params = $.param({search: $.extend(this.state.search, {user_id: Request.user_id, search_type: search_type})});  Request.put('searches/'+this.state.search['id'], search_params, function(){});    Uncaught TypeError: Cannot read property 'lat' of undefined(…)  

So, I would need to send an array of location objects. Is there a specific format in which this array of location object is directly converted to geometry object on the update function? Here is the update function which is called on search update in ruby:

def update      search = Search.find(params[:id])      if search.update_attributes(search_params)        render :json => {:recent => search}, :status => 200      else        render :json => {:error => "Could not update search."}, :status => 422      end    end  

And the search_params is:

def search_params        params.require(:search).permit(          :name,          :user_id,          :q,          :drawn_polygons #This is the column I want to be updated with geometry object        )      end  

Would something like :drawn_polygons => RGeo::Geos::CAPIMultiPolygonImpl work? If it does, what format of :drawn_polygons object do I need to provide?

OR

I need to take the :drawn_polygons as a list of coordinates, and change it to a RGeo::Geos::CAPIMultiPolygonImpl inside the update function? If so, how to do it?

def update      search = Search.find(params[:id])      search_parameters = search_params      drawn_polygons = JSON.parse(URI.decode(search_parameters[:drawn_polygons]))      # Some code to change the search_params[:drawn_polygons] to geometry object, specifically RGeo::Geos::CAPIMultiPolygonImpl      search_parameters(:drawn_polygons) = drawn_polygons      if search.update_attributes(search_parameters)        render :json => {:recent => search}, :status => 200      else        render :json => {:error => "Could not update search."}, :status => 422      end    end  

Scope conditionals for count?

Posted: 13 Nov 2016 01:31 AM PST

How can I get this scope to work with multiple .count?

scope :level_5, -> { (self.accomplished.key.count > 4) && (self.accomplished.adventure.count > 2)  && (self.accomplished.health.count > 2) && (self.accomplished.work.count > 2) }  

I've also tried:

scope :level_5, -> { self.accomplished.key.count > 4, self.accomplished.adventure.count > 2,  self.accomplished.health.count > 2), (self.accomplished.work.count > 2) }  

or

scope :level_5, -> { accomplished.where(key.count > 4, adventure.count > 2,  health.count > 2, work.count > 2) }  

or

scope :level_5, -> { "user.accomplished.key.count > 4" && "user.accomplished.adventure.count > 2" &&  "user.accomplished.health.count > 2" && "user.accomplished.work.count > 2" }  

It will be used for conditionals so if :level_5 then trigger X.

Rails link_to how to show blank when null

Posted: 13 Nov 2016 03:17 AM PST

I have this in my view:

 <td><%= link_to product_sale.product.consignor.try(:NAME), { controller: :consignors, action: :edit, ID: product_sale.product.consignor.try(:ID) }, :target => "_blank" %></td>  

which in product_sale view links to edit consignors for products listed.

Some product doesn't have consignor. When that happens, it shows /consignors/edit

How can I show it blank instead?

Subclass accessing the parent in ruby

Posted: 13 Nov 2016 01:14 AM PST

I'm having a little problem understanding here, I'm trying to get the subclass to access the parent class. Which I believe is class b < a. But after I run the program, it tells me that I have not defined the checking class. Doesn't inheritance define the class? Would I use another def initialize under the checking class with a super to define it? If so what would I initialize?

class Account      attr_accessor :number, :principal, :type        def initialize(initial_deposit)          @number = Bank.size + 1          @principal = initial_deposit.to_f      end        def deposit(amt)          @principal += amt          self.balance          printf "$%.2f successfully deposited\n", amt          printf "Current balance is $%.2f\n", @principal      end        def withdraw(amt)          @principal -= amt          if @principal < 0              puts "Your #{@type} account #{@number} is overdrawn!"              printf "Current account balance: -$%.2f\n", @principal.abs              printf "Please deposit at least $%.2f immediately to avoid additional fees!\n", @principal.abs          else              self.balance              printf "%.2f successfully withdrawn. Current balance is %.2f\n", amt, @principal          end      end  end    class Checking < Account        def          super      end        def balance()          @balance = principal * (1 + interest_rate / 365) ** 365      end    end    # print_menu: displays a nicely formatted menu  #             and prompts the user for a choice  # parameters: none  # return value: none  def print_menu      puts "Welcome to First Acme Banking!"      puts "Please select from the following menu:"      puts "    v - View current balance information"      puts "    c - Create new checking account"      puts "    s - Create new savings account"      puts "    d - Deposit funds into account"      puts "    w - Withdraw funds from account"      puts "    q - Quit"      print "Enter your selection: "  end    # The "main" part of the program  # keeps looping until the user chooses 'q'  # You shouldn't have to write anything in here!  begin      # print the menu and get the choice      print_menu      choice = gets.chomp.downcase        # do different things depending on what choice was entered      case choice.downcase          when "v"              # if Bank is empty, then there are no accounts to display              # so print an error message and continue to main screen              if Bank.empty?                  puts "No accounts yet!"                  print "Press 'enter' to continue..."                  gets              else                  # otherwise iterate over each account                  # and print the balance                  Bank.each do |acct|                      printf "Acct #{acct.number} (#{acct.type}) has an available balance of $%.2f\n", acct.balance                  end                  print "Press 'enter' to continue..."                  gets              end          when "c"              begin Module.const_get("Checking").is_a?(Class)                  # Checking accts don't have a minimum opening balance                  # so we can just create it with a 0 balance and ask                  # for a deposit                  acct = Checking.new                  puts "Your checking account #{acct.number} has been created!"                  print "Would you like to make a deposit (y/n)? "                  deposit = gets.chomp.downcase                  if (deposit.eql? "y")                      print "Enter the deposit amount: "                      amt = gets.to_f                      acct.deposit(amt)                  end                  Bank << acct                  print "Press 'enter' to continue..."                  gets              rescue NameError                  # if you see this message,                  # then you haven't done your homework...!                  puts "You haven't defined the Checking class yet,"                  puts "or you haven't inherited the Checking class from Account!"                  print "Press 'enter' to continue..."                  gets              end          when "s"              begin Module.const_get("Savings").is_a?(Class)                  # Savings accts require a min $1000 opening balance                  # so get the deposit amount first and then create the acct                  print "Please enter an intial deposit (min $1000): "                  amt = gets.to_f                  acct = Savings.new(amt)                  puts "Your savings account #{acct.number} has been created!"                  print "Would you like to make another deposit (y/n)? "                  deposit = gets.chomp.downcase                  if (deposit.eql? "y")                      print "Enter the deposit amount: "                      amt = gets.to_f                      acct.deposit(amt)                  end                  Bank << acct              rescue NameError                  # if you see this message,                  # then you haven't done your homework...!                  puts "You haven't defined the Savings class yet!"                  print "Press 'enter' to continue..."                  gets              end          when "d"              # if Bank is empty, then there's nothing to deposit to...              if Bank.empty?                  puts "No accounts yet!"                  print "Press 'enter' to continue..."                  gets              else                  # otherwise, find the account by number                  # ask for a deposit amount                  # and make the deposit                  print "Enter the account number you wish to deposit funds to: "                  acct_num = gets.to_i                  acct = Bank.find { |a| a.number == acct_num }                  print "Enter the amount you wish to deposit: "                  amt = gets.to_f                  acct.deposit(amt)                  print "Press 'enter' to continue..."                  gets              end          when "w"              # if Bank is empty, then there's nothing to withdraw from...              if Bank.empty?                  puts "No accounts yet!"                  print "Press 'enter' to continue..."                  gets              else                  # otherwise, find the account by number                  # ask for a withdrawal amount                  # and make the withdrawal                  print "Enter the account number you wish to withdraw funds to: "                  acct_num = gets.to_i                  acct = Bank.find { |a| a.number == acct_num }                  print "Enter the amount you wish to withdraw: "                  amt = gets.to_f                  acct.withdraw(amt) # Note, withdrawal checks for overdrafts!                  print "Press 'enter' to continue..."                  gets              end          when "q"              exit      end  end until choice == "q"  

IMPLEMENT CHECKING CLASS HERE Do the following:

1 -- create a constructor that first makes the appropriate call to the Account class constructor (i.e., use super w/ parameters) and sets the type

2 -- define a method called "balance" that computes the principal plus interest according to the following simple formula

  principal = principal * (1 + interest_rate / 365) ** 365  

3 -- Looking at the above, you'll need to create a class variable called @@interest_rate and set it's value to the current checking account interest rate, which is 0.003

This is what I have to do but I'm just trying to get insight on how to even start this out. I'm not looking for the answer, its just all I really have is this

Mocking chain of methods in rspec

Posted: 13 Nov 2016 12:41 AM PST

There are a chain of methods which gets a user object. I am trying to mock the following to return a user in my Factory Girl

@current_user = AuthorizeApiRequest.call(request.headers).result  

I can mock the object up until the call method but I'm stuck at mocking the result method

allow(AuthorizeApiRequest).to receive(:call).and_return(:user)  

Paypal integration with Ruby-on-rails proxy

Posted: 13 Nov 2016 12:33 AM PST

I have a problem with Paypal integration on a website. Can anyone tell how to set proxy for Paypal so that my machine can access Paypal address? Our University server has firewall, and I need to bypass it.

I used Ruby-on-rails code from this site: https://launchschool.com/blog/paypal-payments-with-credit-cards.

Note: It works well on my development station, but doesn't work on production when I deploy, because of proxy; I am using apache2 on my production.

Rails4 Action Controller - undefined method 'length' for nil:NilClass

Posted: 13 Nov 2016 12:06 AM PST

I'm building a messaging system from scratch for one of my projects. Everything was working well but I just had the following error: NoMethodError in MessagesController#index followed by undefined method 'length' for nil:NilClass. I couldn't find any answer that correspond to my case, unfortunately.

I give you conversations_controller.rb, messages_controller.rb, the models and the routes (and logs):

conversations_controller.rb

class ConversationsController < ApplicationController    before_action :authenticate_user!      def index      @users = User.all      @conversations = Conversation.all    end      def create      if Conversation.between(params[:sender_id], params[:recipient_id]).present?        @conversation = Conversation.between(params[:sender_id], params[:recipient_id]).first      else        @conversation = Conversation.create!(conversation_params)      end      redirect_to conversation_messages_path(@conversation)    end      private      def conversation_params      params.permit(:sender_id, :recipient_id)    end    end  

messages_controller.rb :

class MessagesController < ApplicationController      def index      if @messages.length > 10        @over_ten = true        @messages = @messages[-10..-1]      end      if params[:m]        @over_ten = false        @messages = @conversation.messages      end      if @messages.last        if @messages.last.user_id != current_user.id          @messages.last.read = true;        end      end      @message = @conversation.messages.new    end      def new      @message = @conversation.messages.new    end      def create      @message = @conversation.messages.new(message_params)      if @message.save        redirect_to conversation_messages_path(@conversation)      end    end      private      def message_params      params.require(:message).permit(:body, :user_id)    end  end  

conversation.rb :

class Conversation < ActiveRecord::Base    belongs_to :sender, foreign_key: :sender_id, class_name: 'User'    belongs_to :recipient, foreign_key: :recipient_id, class_name: 'User'      has_many :messages, dependent: :destroy      validates_uniqueness_of :sender_id, scope: :recipient_id      scope :between, -> (sender_id,recipient_id) do      where("(conversations.sender_id = ? AND conversations.recipient_id = ?)              OR (conversations.sender_id = ? AND conversations.recipient_id = ?)",              sender_id,recipient_id, recipient_id,sender_id)      end  end  

message.rb :

class Message < ActiveRecord::Base    belongs_to :conversation    belongs_to :user      validates_presence_of :body, :conversation_id, :user_id      def message_time      created_at.strftime("%m/%d/%y at %l:%M %p")    end  end  

Routes.rb :

Rails.application.routes.draw do      get 'messages/index'      get 'messages/new'      get 'conversations/index'      get 'dashboard/index'      get 'dashboard/trips'      get 'dashboard/messages'      get "welcome/index"      resources :conversations do      resources :messages    end      devise_for :users      authenticated :users do      root to: 'dashboard#index', as: :authenticated_root    end      root "welcome#index"  end  

Here, the logs:

Started GET "/conversations/5/messages" for ::1 at 2016-11-13 16:45:38 +1030  Processing by MessagesController#index as HTML    Parameters: {"conversation_id"=>"5"}  Completed 500 Internal Server Error in 5ms (ActiveRecord: 0.0ms)    NoMethodError (undefined method `length' for nil:NilClass):    app/controllers/messages_controller.rb:4:in `index'        Rendered /Users/JUSTINE/.rvm/gems/ruby-2.3.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_source.erb (3.7ms)    Rendered /Users/JUSTINE/.rvm/gems/ruby-2.3.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_trace.html.erb (2.1ms)    Rendered /Users/JUSTINE/.rvm/gems/ruby-2.3.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/_request_and_response.html.erb (1.7ms)    Rendered /Users/JUSTINE/.rvm/gems/ruby-2.3.0/gems/actionpack-4.2.6/lib/action_dispatch/middleware/templates/rescues/diagnostics.html.erb within rescues/layout (53.1ms)    Rendered /Users/JUSTINE/.rvm/gems/ruby-2.3.0/gems/web-console-2.3.0/lib/web_console/templates/_markup.html.erb (0.5ms)    Rendered /Users/JUSTINE/.rvm/gems/ruby-2.3.0/gems/web-console-2.3.0/lib/web_console/templates/_inner_console_markup.html.erb within layouts/inlined_string (0.3ms)    Rendered /Users/JUSTINE/.rvm/gems/ruby-2.3.0/gems/web-console-2.3.0/lib/web_console/templates/_prompt_box_markup.html.erb within layouts/inlined_string (0.4ms)    Rendered /Users/JUSTINE/.rvm/gems/ruby-2.3.0/gems/web-console-2.3.0/lib/web_console/templates/style.css.erb within layouts/inlined_string (0.3ms)    Rendered /Users/JUSTINE/.rvm/gems/ruby-2.3.0/gems/web-console-2.3.0/lib/web_console/templates/console.js.erb within layouts/javascript (40.4ms)    Rendered /Users/JUSTINE/.rvm/gems/ruby-2.3.0/gems/web-console-2.3.0/lib/web_console/templates/main.js.erb within layouts/javascript (0.4ms)    Rendered /Users/JUSTINE/.rvm/gems/ruby-2.3.0/gems/web-console-2.3.0/lib/web_console/templates/error_page.js.erb within layouts/javascript (0.7ms)    Rendered /Users/JUSTINE/.rvm/gems/ruby-2.3.0/gems/web-console-2.3.0/lib/web_console/templates/index.html.erb (91.6ms)  

I hope it will be helpful for you and we will be able to find the answer :)

Cheers

Rails app, single login for two sub domains

Posted: 12 Nov 2016 11:40 PM PST

I'm creating portal for academic domain where user can be both 'Student' and 'Teacher'. User can choose which dashboard they want to go while login or switch their dashboard after login.

I'm not sure what is the best way to architect the rails app so single login can enable user to use both sub-system (Student and Teacher).

I'm also thinking of having two separate rails apps running on subdomain student.mydomain.com and teacher.mydomain.com. In this case, again single login should work for both domain and user can switch from one app to other without login again.

Upload file to remote URL (etc. another LAN computer) with CarrierWave

Posted: 12 Nov 2016 11:11 PM PST

My project at school is create a demo distributed system. I created a web app that could upload and share files (sth like a small dropbox system).

In this project, I setup 1 virtualbox machine for each part. In rails app, I'm using CarrierWave gem to save uploaded files.

Follow CarrierWave doc here, I have two options: 1 is store files locally in public folder, or use a 3rd party storage like S3 ... But my problem here is I don't know how to make CarrierWave save files to to storage machine (the bottom part).

enter image description here

Can't import bootstrap

Posted: 12 Nov 2016 11:07 PM PST

I've looked through many solutions but still can't find the solution to my problem. I'm using Rails 5.0.0.1, running on Windows OS. I've done bundle install and restarted the server, as well as downgrading the sass-rails but I can't seem to fix the issue.

The gems I needed for this: bootstrap-sass <3.3.7> sass-rails <5.0.6, 3.2.0>

In my application.scss file:

 @import "bootstrap-sprockets";   @import "bootstrap";   

In my application.js file:

 //= require jquery   //= require jquery_ujs   //= require turbolinks   //= bootstrap-sprockets   //= require_tree .  

The error page

Please help! Thanks!

How to handle authentication callback in an API backend? Rails API + React Fronetend + Facebook

Posted: 12 Nov 2016 10:42 PM PST

I have a Rails 5 API only backend. I have two routes as such:

  # facebook link url    # GET /accounts/facebook_url    def facebook_url      @oauth = Koala::Facebook::OAuth.new(        ENV['FACEBOOK_APP_ID'],        ENV['FACEBOOK_SECRET'],        facebook_callback_accounts_url      )      # @oauth.url_for_oauth_code # create oauth url      url = @oauth.url_for_oauth_code      render json: url # hanlde using serializer?    end      # facebook will post to this url with the code    # GET /accounts/facebook_callback?code=fadsdfaadsf    def facebook_callback      @oauth = Koala::Facebook::OAuth.new(        ENV['FACEBOOK_APP_ID'],        ENV['FACEBOOK_SECRET'],        facebook_callback_accounts_url      )      token = @oauth.get_access_token(params[:code])    end  

In my react app, I get the url for authentication from the facebook_url route and I redirect the user to that route. Now facebook send me the token. I am able to get up to this point. Now my problem is that how will my frontend know that token was received successfully or not?

If this was only a rails application, I could use different redirects based on status. It seems more like an architecture based question rather than rails specific. Any help is appreciated.

No comments:

Post a Comment