Sunday, August 7, 2016

How can I check the authorization in Cancancan in Ruby on Rails each time the user calls that action? | Fixed issues

How can I check the authorization in Cancancan in Ruby on Rails each time the user calls that action? | Fixed issues


How can I check the authorization in Cancancan in Ruby on Rails each time the user calls that action?

Posted: 07 Aug 2016 07:41 AM PDT

I'm using Ruby on Rails 5 and I want that depending of the role of a User, the user can post 5 Posts or 10 or 15, and that is just a part of the several possible situations that I have to check for Authorization (for things that are not Posts for instance I have other situations that are a bit more complex), so I started using Cancancan (v 1.15.0) few days ago to don't make the User model too huge, so this way I have one class for each Role and in ability.rb I just merge the classes depending on the Role.

The problem is that using Cancancan apparently it checkes the Authorization only once. For example in Creating a Post, In Post#create the first line of code is:

authorize! :create, Post  

In the Role class of the user, I have this code:

  if user.posts.size < 10      Rails.logger.debug "If-size: #{user.posts.size}"      can :create, Post    else      Rails.logger.debug "Else-size: #{user.posts.size}"      cannot :create, Post    end  

I have some tests with RSpec and I see the first time the current_user (the one with that specific role) creates a Post using the controller (I mean, not by FactoryGirl or any other way that is not using the controller), it appears in log/test.log:

If-size: 0  

But neither the Else nor the If appears ever again in the log, it doesn't matter how many Posts I create by the Controller, it only evaluates this condition the first time and the User get authorized to creates as many Posts as he wants because the first time the condition in the If is true and it is not evaluated each time the method create of the controller Post is called.

What can I do? Thanks! :)

How do I install masonry or other javascript in rails? (not using gems)

Posted: 07 Aug 2016 07:37 AM PDT

I wanted Masonry for my Rails 4.2 project and initially installed it via the masonry-rails gem and then wasted an evening until I realized that the gem was using an outdated version of Masonry. This will be my first attempt to add javascript to my Rails app without a gem. From the installation docs the options are: Download, CDN, Package managers (bower/npm)

I used CDN by simply adding

<script src="https://npmcdn.com/masonry-layout@4.1/dist/masonry.pkgd.min.js"></script>  

to the top of my index.html.erb view file that will use the script. Is this correct?

What is the advantage/disadvantage of using CDN instead of Download or Package managers and if I want to add masonry.pkgd.min.js manually to my project how would i do so?

How to redirect user to his profile using unique link in Rails?

Posted: 07 Aug 2016 07:24 AM PDT

I have a Rails app using mongodb. I have a model Bot with an attribute link (string). I want user to redirect to its profile using unique link which consists of host and link (e.g. http://localhost:3000/bots/home/06b5f629b3fbec5612ef79dd14d8d762).

routes.rb

get 'bots/home/:link' => 'bots#home'  

bots_controller.rb

 def home      @hu = request.url[32..-1]      @bots = Bot.where(link: @hu)    end  

So I try to retrieve this unique value from request and match it to link attribute of the Bot in db but it doesn't work.

When to use a model vs. an enum?

Posted: 07 Aug 2016 07:13 AM PDT

I have a Role model that I'd like to identify by type. It would be either a company related, meaning the role was done through a company or an artist related role, meaning the role was done by one artist. Would creating a model specifically for this use-case scenario be overkill? Does the use of enums fit best in this situation? Overall when should you use one over the other?

Using omniauth-google-oauth2 gem in rails 2.3.8 and ruby 1.8.7

Posted: 07 Aug 2016 07:32 AM PDT

How to do authentication using omniauth-google-oauth2 gem in rails 2.3.8? I have installed omniauth-google-oauth2 gem of version 0.1.15. But i dont know how to proceed further.

Passing ID from one controller to another

Posted: 07 Aug 2016 05:50 AM PDT

So I am developing a job portal website, and I am looking to pass the current job ID over to the "job applications" controller #new method, but I am having issues being able to do so.

So when a user clicks the "Job_applications#new", It gets the current page job_id.

Models

Class Job     has_many :job_applications  end    Class JobApplication    belongs_to :job  end  

In my Job_Applications Controller

def create      @job = Job.find(params[:id])      *Additional save & Redirect methods*  end  

In my View I have the following code

<%= link_to "Apply Now",new_job_application_path(:id => @job.id), class: "btn btn-primary" %>  

I know I am doing something stupid here, Ideally, I would like to pass the job id without it being in the URL

Example

domain.com/job_application/new  

However this method shows this

domain.com/job_application/new?id=3  

Any help greatly appreciated

Rails Association working only one way

Posted: 07 Aug 2016 06:47 AM PDT

My model "Preconditions" creates relationships between records in the "Assignments" model, so that one assignment can be a pre-requisite for another assignment.

In the console, Assignment.find(3).preassigns outputs the second record from the Assignment table, as I expect. However, the inverse is not working. Assignment.find(2).mainassigns returns an empty set.

precondition.rb

class Precondition < ApplicationRecord      belongs_to :mainassign, class_name: "Assignment"      belongs_to :preassign, class_name: "Assignment"  end  

assignment.rb

class Assignment < ApplicationRecord      belongs_to  :seminar      has_many    :scores, dependent: :destroy        has_many    :preconditions, class_name: "Precondition",                                  foreign_key: "mainassign_id",                                  dependent: :destroy      has_many    :mainconditions, class_name: "Precondition",                                  foreign_key: "preassign_id",                                  dependent: :destroy        has_many    :preassigns, through: :preconditions, as: :mainassign, source: :preassign      has_many    :mainassigns, through: :preconditions, as: :preassign, source: :mainassign        validates :name, presence: true, length: { maximum: 40 }      validates :seminar_id, presence: true      validates :possible, presence: true      validates_numericality_of   :possible, only_integer: true  end  

Based on similar questions, I've tried adding a polymorphic tag in the Preconditions table, like so:

belongs_to :mainassign, class_name: "Assignment", polymorphic: true  

This caused an error, but the log suggested that I try a source_type, so I tried adding that to the assignments model, like so:

has_many    :mainassigns, through: :preconditions, as: :preassign, source: :mainassign, source_type: "Assignment"  

But that resulted in an SQL column not found error.

Thank you in advance for any insight.

Rails: when do we must put :: before some classes for rails understand base class

Posted: 07 Aug 2016 06:19 AM PDT

In Ruby, I understand that ::ClassName for calling class at base module. For example, here is my code:

module HHT    module V1      module OfflineCheckIn        class PutOfflineCheckInProductsApi < ApplicationApi          put 'offline' do            ActiveRecord::Base.transaction do              OfflineCheckIn.create(check_in_param) # exception here            end          end        end      end    end  end  

When I run, I meet exception:

NoMethodError (undefined method `create' for HHT::V1::OfflineCheckIn:Module)

As I understand, Rails understand that OfflineCheckIn currently inside module HHT::V1::OfflineCheckIn, so I must call at base class ::OfflineCheckIn. Thing that I don't understand is: at another controller, some previous programmer implements same way with me, but he doesn't need to call :: before model.

So my question is: when we don't need to use :: before class and rails can understand that is base class ?

Thanks

Rails passenger not working with apache

Posted: 07 Aug 2016 06:13 AM PDT

I am trying to run rails using passenger and apache2 to I have followed everything but I am getting this problem.

Raw process output:    *** ERROR ***: Cannot execute /home/nilay/.rbenv/versions/2.3.1/lib/ruby: Permission denied (13)  

I don't know how to fix it my apachecof file is like this:

<VirtualHost *:80>  ServerName nilay.com  ServerAlias nilay.com  ServerAdmin webmaster@localhost  PassengerRuby /home/nilay/.rbenv/versions/2.3.1/lib/ruby  DocumentRoot /home/nilay/rails/pipe/public  RailsEnv development  ErrorLog ${APACHE_LOG_DIR}/error.log  CustomLog ${APACHE_LOG_DIR}/access.log combined  <Directory "/home/nilay/rails/pipe/public">      Options FollowSymLinks      Require all granted  </Directory>  

And my rbenv path is like this:

/home/nilay/.rbenv/versions/2.3.1/lib/ruby  

I don't know what it the problem please help me fix this issue.

how to get data from two different join tables

Posted: 07 Aug 2016 04:22 AM PDT

i have two Join table first one between alarm_id | list_id and the other one between list_id | car_id what to do to get in the alarm show, the cars in each list, i tried to use has_many :cars :through => lists, but it doesn't work any help please

Patch request in Backbonejs

Posted: 07 Aug 2016 04:03 AM PDT

I am trying to partially update an model using patch request. I wrote like this:

@model.save(null, {    silent: true    patch: true  })  

But the server is returning a 405 error. I couldn't figure out the reason, can anyone help?

My backend is a rails application.

Thanks

<%= content_for :my_region_name do %> in Phoenix/Elixir

Posted: 07 Aug 2016 03:54 AM PDT

How can I define a named render region in an layout? This defines a default region which I can overwrite in a child view:

<%= render @view_module, @view_template, assigns %>  

But I want to create multiple <%= render @view_module, @view_template, assigns %> in the an layout and be able to overwrite some of them in child views. In rails I can do that by:

<%= yield :my_region_name %>      <%= content_for :my_region_name do %>  

current_page? isn't working with routes with optional params

Posted: 07 Aug 2016 03:45 AM PDT

Here's the route:

get "search(/:search)", to: "posts#index", as: :search  

Now if I'm at /search/somethingsomething and the view is:

- if current_page?(search_path)    = (do something)  

then that something isn't being done. If I remove the parenthesis around :search, however (i.e. get "search/:search" ...), then it works. What gives?

Build QR code and display image without saving

Posted: 07 Aug 2016 03:22 AM PDT

I want to build QR Code of a particular string/url. After building, without saving I want to display the display the image. I don't want to persist the image. Something like http://example.com/qrcode?code=LOL, should display the QR code for the string LOL.

Platform : Ruby on Rails 4

Thanks.

Activemerchant, checkout paypal sandbox express: transaction errors Internal Error, 10001

Posted: 07 Aug 2016 02:51 AM PDT

I try test paypal sandbox checkout.

  • Step express [OK] => token, PayerID
  • Set params token, PayerID to form and submit PLACE_ORDER
  • Then purchase . It response error
pp_response = pp_method.purchase(cent_format(order.total),      {          ip: ENV['IP'],          items: payment_details,          token: params[:token],          payer_id: params[:PayerID]      }  )  
#<ActiveMerchant::Billing::PaypalExpressResponse:0x007f83b0cf3650   @authorization=nil,   @avs_result={"code"=>nil, "message"=>nil, "street_match"=>nil, "postal_match"=>nil},   @cvv_result={"code"=>nil, "message"=>nil},   @emv_authorization=nil,   @error_code=:processing_error,   @fraud_review=false,   @message="Internal Error",   @params=    {"timestamp"=>"2016-08-07T09:08:10Z",     "ack"=>"Failure",     "correlation_id"=>"5db741902d114",     "version"=>"124",     "build"=>"000000",     "do_express_checkout_payment_response_details"=>nil,     "message"=>"Internal Error",     "error_codes"=>"10001",     "Timestamp"=>"2016-08-07T09:08:10Z",     "Ack"=>"Failure",     "CorrelationID"=>"5db741902d114",     "Errors"=>{"ShortMessage"=>"Internal Error", "LongMessage"=>"Internal Error", "ErrorCode"=>"10001", "SeverityCode"=>"Error"},     "Version"=>"124",     "Build"=>"000000",     "DoExpressCheckoutPaymentResponseDetails"=>nil},   @success=false,   @test=true>  

But when I check 2 account sandbox, both tell status 'Success'

How to configure apache in local development in rails

Posted: 07 Aug 2016 02:41 AM PDT

I am trying setup a loacl domain on my pc for that I have apache server install I want to open my rails s inside this abcd.com instead of 127.0.0.1:3000. In my host I have changed host file like this:

127.0.0.1   localhost  127.0.0.1   abcd.com  

But when I am trying to open abcd.com with this command I am getting this message:

 Address already in use - bind(2) for "127.0.0.1" port 80 (Errno::EADDRINUSE)  

When I stop apache it works on localhost any help

(Mathematical) optimization in Ruby

Posted: 07 Aug 2016 03:30 AM PDT

I am trying to build in an algorithm in my Ruby program that optimizes an objective function subject to a certain restricted set of values that my 'unknown' can take. The function should take the objective function, the upper limit the lower limit and return the value for 'x' that maximized the objective function within this range. If I would like to do something similar in R I can simply use a function such as optim (https://stat.ethz.ch/R-manual/R-devel/library/stats/html/optim.html). But I don't want to use R in this case neither want to use a gem that creates an R interface. Is there any gem to perform such operations directly in Ruby (maybe even for multiple unknown variables)?

Edit: The reason I don't want to use an R interface is because I want to be able to deploy the application without having to install anything, such as R or GLPK on the server

How rails do nested form in one form?

Posted: 07 Aug 2016 04:43 AM PDT

The scenario is that, I want to design a Post form which is used to record what fruit I eat in one meal, include picture, content, many kind of fruit. The model relationship is that,

Post has_many fruits  Fruit belong_to post  

I usee Jquery-ui to make autocomplete in order to help user type their fruit. After they type there fruit tag, it will create a tag under the input field. Like this

enter image description here

However how to I create this in form? I thought about dynamic nested form, but I don't want there're a lots of form, I wish there would be only one input and do the same thing with dynamic nested form.

Here is the github, please let me know if I need to provide more information.

What Rails-ActiveRecord association to use for this?

Posted: 07 Aug 2016 02:49 AM PDT

Let's say I have a computer model.

This computer has 2 characteristics:

  • a name.

  • a price.

How would these characteristics be associated with the Computer Model? (Ex: belongs_to, has_one,yadda yadda)

Unicorn Error log

Posted: 07 Aug 2016 12:57 AM PDT

I am trying to deploy my rails app to digitalocean with postgresql database . my database.yml looks like this

default: &default    adapter: postgresql    encoding: unicode      pool: 5    host: localhost    username: rails    password:     production:    <<: *default    database: myorganicmantra_production    username: rails    password:   

i did rake db:create and it shows myorganicmantra_production already exists but when i am restarting unicorn server and loking to unicorn.log there is line like ]

ERROR -- : FATAL:  database "myorganicmantra_production" does not exist   (ActiveRecord::NoDatabaseError)  

and eventually it is shwing 504 timeout on the webpage

here is my /etc/default/unicorn file

APP_ROOT=/home/rails/myorganicmantra    # Server's config.rb, it's not a rack's config.ru  CONFIG_RB=/etc/unicorn.conf    # Where to store PID, sh'ld be also set in server's config.rb, option "pid".  PID=/var/run/unicorn.pid  RAILS_ENV="production"  UNICORN_OPTS="-D -c $CONFIG_RB -E $RAILS_ENV"    PATH=/usr/local/rvm/rubies/ruby-2.2.1/bin:/usr/local/sbin:/usr/bin:/bin:/sbin:/usr/local/rvm/bin:/usr/local/rvm/gems/ruby-2.2.1@global/bin:/usr/local/rvm/gems/ruby-2.2.1/bin/  export GEM_HOME=/usr/local/rvm/gems/ruby-2.2.1  export GEM_PATH=/usr/local/rvm/gems/ruby-2.2.1:/usr/local/rvm/gems/ruby-2.2.1@global  DAEMON=/usr/local/rvm/gems/ruby-2.2.1/bin/unicorn    # Generate by running `rake -f /home/rails/rails_project/Rakefile secret`  export SECRET_KEY_BASE=7a4a64cb96134c5fc9b621c6c475740fb119286282ef9bdfb7d858c53c3eac7d8496412be3f43415cf98e568c65d851422baef810ac87bd28d52eef8cb49c235  export APP_DATABASE_PASSWORD=OREXemjvCj  

Why generate scaffold won't work?

Posted: 07 Aug 2016 12:45 AM PDT

I'm currently following Rails tutorial by Michael Hartl here.

To proceed with my application I did the following(as the book said):

rails generate scaffold User name:string email:string  

However I'm getting the following errors:

enter image description here

SystemStackError: stack level too deep caused by Nokogiri

Posted: 07 Aug 2016 12:48 AM PDT

I'm trying to call document.at_css("a[data-field=url]") on a web page but I'm getting SystemStackError. I'm aware that this is caused by overflowing the memory stack but I have no idea how to solve this. Following is my stack trace,

from /Users/kilimchoi/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8/lib/nokogiri/css/parser_extras.rb:55:in `new'  from /Users/kilimchoi/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8/lib/nokogiri/css/parser_extras.rb:55:in `initialize'  from /Users/kilimchoi/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8/lib/nokogiri/css.rb:23:in `new'  from /Users/kilimchoi/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8/lib/nokogiri/css.rb:23:in `xpath_for'  from /Users/kilimchoi/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8/lib/nokogiri/xml/searchable.rb:198:in `block in xpath_query_from_css_rule'  from /Users/kilimchoi/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8/lib/nokogiri/xml/searchable.rb:197:in `map'  from /Users/kilimchoi/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8/lib/nokogiri/xml/searchable.rb:197:in `xpath_query_from_css_rule'  from /Users/kilimchoi/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8/lib/nokogiri/xml/searchable.rb:192:in `block in css_internal'  from /Users/kilimchoi/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8/lib/nokogiri/xml/searchable.rb:192:in `map'  from /Users/kilimchoi/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8/lib/nokogiri/xml/searchable.rb:192:in `css_internal'  from /Users/kilimchoi/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8/lib/nokogiri/xml/searchable.rb:107:in `css'  from /Users/kilimchoi/.rvm/gems/ruby-2.3.0/gems/nokogiri-1.6.8/lib/nokogiri/xml/searchable.rb:118:in `at_css'  

heroku: lookup_asset_for_path on heroku (Rails 5)

Posted: 06 Aug 2016 10:26 PM PDT

Gem file:

ruby "2.3.1"  gem 'rails', '~> 5.0.0'  gem 'puma', '~> 3.0'  gem 'sass-rails', '~> 5.0'  gem 'uglifier', '>= 1.3.0'  gem 'jquery-rails'  gem 'turbolinks', '~> 5'  gem 'jbuilder', '~> 2.5'  gem 'bootstrap-sass', '~> 3.3', '>= 3.3.7'    group :production do      gem 'pg'      gem 'rails_12factor'  end  

application.html.erb

<!-- Include style per-controller - vendor plugins -->      <%= stylesheet_link_tag params[:controller] if ::Rails.application.assets.find_asset("#{params[:controller]}.css") %>    <!-- Main css styles -->      <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track' => true %>    <!-- Main javascript files -->      <%= javascript_include_tag 'application', 'data-turbolinks-track' => true %>    <!-- Include javascript per-controller - vendor plugins -->      <%= javascript_include_tag params[:controller] if ::Rails.application.assets.find_asset("#{params[:controller]}.js") %>  

config/application.rb

config.assets.precompile += [ 'style.css', 'style.js' ]  

config/environments/production.rb

config.assets.compile = true  

Command: precompile assets

RAILS_ENV=production bundle exec rake assets:precompile  

Note:

  • its works for local development
  • but when i push it to heroku, got error:

undefined method `lookup_asset_for_path'

load a mesh with three.js in ruby on rails

Posted: 06 Aug 2016 10:08 PM PDT

I am trying to map a load a mesh into my three.js animation in my ruby on rails project. I use the following code:

function initCube(){     var material = new THREE.MeshBasicMaterial({          wireframe: true,          color: 'blue'      });      group = new THREE.Object3D();      var loader = new THREE.JSONLoader();      loader.load('<%= asset_path 'cube.js' %>', modelLoadedCallback);  }    function modelLoadedCallback(geometry) {      mesh = new THREE.Mesh( geometry, material );      group.add(mesh);      scene.add( group );  }  

But somehow its not doing anything. The cube.js file is in my assets/images folder. Am I using the paths wrong? If i just load a sphere like following it works just fine.

geometry = new THREE.SphereGeometry(radius, segments, rings);  character = new THREE.Mesh( geometry, characterMaterial);  

Rails 4 - Rolify - how to assign a scoped role

Posted: 07 Aug 2016 01:27 AM PDT

I'm trying to figure out how to assign a role to a user in Rails 4, using rolify.

My use case is:

I want to assign global roles to users who operate the app.

I want to assign scoped roles to all customers. Each customer belongs to an organisation. Any role they are assigned will be confined to the organisation they belong to.

How can I achieve this in rails? At this stage, I'm stuck with the logic of how to do this.

display a corresponding button and it's link in rails

Posted: 07 Aug 2016 12:05 AM PDT

I have a structured layout here in Rails 5 ERB that renders a partial for each data passed in as locals via a json file for data, but each of them either has 1 or 2 buttons with it's corresponding links inside, I also want to change the button's title for each link it corresponds to. I've already implemented it but I feel that putting all the logic in the view is kind of unappealing is there a way that i can put this in a helper that displays a specific button for each of their links inside of the json file?

I basically want to achieve this

Wireframe

data.json

[{    "github": "https://github.com/",    "heroku": "https://heroku.com/",    "button": [{"github": "github", "heroku": "heroku", "codepen": "codepen", "behance": "behance"}]  },  {    "github": "https://github.com/",    "heroku": "https://heroku.com/",    "button": [{"github": "github", "heroku": "heroku", "codepen": "codepen", "behance": "behance"}]  },  {    "codepen": "https://codepen.com/",    "button": [{"github": "github", "heroku": "heroku", "codepen": "codepen", "behance": "behance"}]  },  {    "codepen": "https://behance.com",    "button": [{"github": "github", "heroku": "heroku", "codepen": "codepen", "behance": "behance"}]  }]  


application_helper.rb

  def portfolio_section(title, &block)      render(:partial => 'editable-sections/portfolio-section',       :locals => {:title => title, :block => block})    end  


index.html.erb controller/template

<%= portfolio_section('Portfolio') do %>    <!-- nested partials -->    <!--  Send data from our json file and pass in local variable for it to be interpolated  -->    <% @data.each do |data| %>        <%= render(:partial => 'editable-sections/panels/panel', :locals => {:data => data})%>    <% end %>  <% end %>  

_panel.html.erb /partial

  <!-- _panel.html.erb -->     <div class="btn-position">       <% if data["github"] && ["heroku"].present?%>         <a href="<%= data["github"] %>" target="_blank" class="btn btn-sharp">            <%= data["button"][0]["github"]%>         </a>         <a href="<%= data["heroku"] %>" target="_blank" class="btn btn-sharp">           <%=data["button"][0]["heroku"] %>         </a>         <% elsif data["codepen"].present?%>         <a href="<%= data["codepen"] %>" target="_blank" class="btn btn-sharp">            <%= data["button"][0]["codepen"]%>         </a>         <% elsif data["behance"].present?%>         <a href="<%= data["behance"] %>" target="_blank" class="btn btn-sharp">            <%= data["button"][0]["behance"]%>         </a>       <% end %>     </div>  

vue.js and rails erb: How to place v-model tag inside erb input

Posted: 06 Aug 2016 10:05 PM PDT

I am currently trying to include a vue.js v-model into my erb form input tag and I cannot find the right syntax.

Here is how my code currently looks:

<div class="field">     <%= f.text_field :first_name, v-model="firstname" %>  </div>  

I would very much appreciate any idea here. Thanks!

Rails: ruby class name must base on file name?

Posted: 06 Aug 2016 11:16 PM PDT

I'm learning rails 5.0. When I learn Ruby, I know that ruby file name can be different with class name inside. But when I move to rails, I see that ruby file name and class name must have same format. For example, a class name CheckInDetail will be in check_in_detail.ruby. I also see that the module name must be matched with directory name. For example, module authentication must be inside authentication directory. Some example for my conclusion is:

  1. rspec: class name must base on file name.
  2. grape: class name must base on file name. Also module name must be matched with directory.

If I don't follow those convention, when compiling rails will throw exception. I don't see those conventions on those library github pages. Will this true for whole rail project, with all libraries ?

Rails One-to-one Child Attribute Accessed as Self Attribute

Posted: 07 Aug 2016 12:11 AM PDT

It's been a few year since I did any Rails development. There used to be a way to access a child attribute, in a one-to-one relationship, as that model's attribute.

So for instance, if you had two models: Person and Address, and they had a 1:1 relationship, you could pull back @person.zip_code, instead of @person.address.zip_code.

This used to be easy to do when you could explicitly define the accessible attributes in the model. It seems this is gone now in Rails 4.

Any ideas?

How to filter search results in rails

Posted: 06 Aug 2016 08:40 PM PDT

Im using searchkick to search my database and I have the initial search working, but I want to have the user able to select from categories to further refine the search results. Right now everytime I search it is searching all the recipes and doesnt maintain previous results. Im using links to apply the filter and not resubmitting a form which is what most examples I find are doing.

Heres my index from my controller:

def index      @recipes = RecipeSearch.new(query: params[:search], options: params).search   end  

Which that calls a different class (to keep controller clean) which calls this for the search function:

def search          constraints = {              aggs: [:cuisines, :techniques, :ingredients]          }            constraints[:where] = where          constraints[:order] = order          puts query          puts constraints          Recipe.search query, constraints      end  

The where and order just add to the constraints and those work fine. I know I need to change the "Recipe.search" part to call search on the old list (if thats even possible) or modify the query variable to include the old params but not sure how to recall those.

No comments:

Post a Comment