Menu
  • HOME
  • TAGS

Virtual Attribute in Rails 4

Tag: ruby-on-rails,ruby,ruby-on-rails-4,virtual-attribute

I have a model of product and I need to write in the _form view , the number of the product that an admin wants to insert. I have another table with the Supply (number of product) so in my product table I don't have the attribute quantity , but I have just the supply_id (that links my two tables of product and supply)

Since I don't have the quantity in my product table, I used a virtual attribute on Product.

I had to change the view of the new and edit product cause in the new I want the field quantity but in the edit I don't want (cause I use another view to do this) So, I deleted the partial _form and created separate view. Also, I had to set in the controller of products that if I want to update a product, i have to call a set_quantity callback, cause I have to insert a "fake" value to fill the params[:product][:quantity]. This , because I setted the validation presence true ,on the quantity virtual field in the product model. I want to know , if all this story is right (it works , but I want a suggestion about the programming design of this story. Cause I don't like the fact that I give a fake value to fill the quantity field when I have to update a product)

Controller:

class ProductsController < ApplicationController
    include SavePicture 
    before_action :set_product, only: [:show, :edit, :update, :destroy]
    before_action :set_quantita, only: [:update]
    ....

    def set_quantita
       params[:product][:quantita]=2  #fake value for the update action
    end
    ....
end

Model:

class Product < ActiveRecord::Base
    belongs_to :supply ,dependent: :destroy
    attr_accessor :quantita
    validates :quantita, presence:true
end

Can you say me if there is a better way to fill the param[:product][:quantity] in the case of the update action? Cause i don't like the fact that i give it the value of 2. Thank you.

Best How To :

Instead of using attr_accessor you could create custom getter/setters on your product model. Note that these are not backed by an regular instance attribute.

Also you can add a validation on the supply association instead of your virtual attribute.

class Product < ActiveRecord::Base
  belongs_to :supply ,dependent: :destroy
  validates_associated :supply, presence:true

  # getter method
  def quantita
    supply
  end

  def quantita=(val)
    if supply
      supply.update_attributes(value: val)
    else
      supply = Supply.create(value: val)
    end
  end
end

In Ruby assignment is actually done by message passing:

product.quantita = 1

Will call product#quantita=, with 1 as the argument.

Another alternative is to use nested attributes for the supply.

class Product < ActiveRecord::Base
  belongs_to :supply ,dependent: :destroy
  validates_associated :supply, presence:true
  accepts_nested_attributes_for :supply
end

This means that Product accepts supply_attributes - a hash of attributes.

class ProductsController < ApplicationController

  #...
  before_action :set_product, only: [:show, :edit, :update, :destroy]

  def create
    # will create both a Product and Supply
    @product = Product.create(product_params)
  end

  def update
    # will update both Product and Supply
    @product.update(product_params)
  end

  private

  def product_params
    # Remember to whitelist the nested parameters!
    params.require(:product)
          .allow(:foo, supply_attributes: [:foo, :bar])
  end
  # ...
end

How to send a mail by postfix mail server with rails?

ruby-on-rails,email,mailer

You need to change the delivery_method from :smtp to :sendmail config.action_mailer.delivery_method = :sendmail ...

Loop until i get correct user

ruby,redis

Change if to while: while ["user_4", "user_5"].include?(@randUser = @redis.spop("users")) do @redis.sadd("users", @randUser) end $user_username = @redis.hget(@randUser, "username") $user_password = @redis.hget(@randUser, "password") Please note, that you actually mixed up receiver and parameters on Array#include?...

How to pass array in rails 4 strong parameters

ruby-on-rails,arrays

According to the docs https://github.com/rails/strong_parameters#permitted-scalar-values: The permitted scalar types are String, Symbol, NilClass, Numeric, TrueClass, FalseClass, Date, Time, DateTime, StringIO, IO, ActionDispatch::Http::UploadedFile and Rack::Test::UploadedFile. To declare that the value in params must be an array of permitted scalar values map the key to an empty array: params.permit(:id => []) If...

ActiveAdmin ::Show 4 textbox in active admin using has_many relationship

ruby-on-rails,gem,activeadmin

Add the following to your Polls Controller- def new @poll = Poll.new 4.times do @poll.answers.build end end ...

Ruby boolean logic: some amount of variables are true

ruby

[a, b, c].count(true) < 2 ........................

RoR Tutorial Chapter 3 - Guard detects changes but doesn't fully execute tests

ruby-on-rails,railstutorial.org,minitest,guard

2 tests, 2 assumptions, 0 failures, 0 errors, 0 skips means guard successfully ran 2 tests containing two assumptions (assertions). The messages in the debug log are telling you of missing dependencies. You could save yourself a big headache and use the free cloud 9 and heroku setup Hartl suggests,...

Showing and editing has_many objects in Rails

ruby-on-rails,ruby-on-rails-4

Since you need to support both (POST /milestones and POST /projects/:project_id/milestones) the project_id to the form: <%= form_for [@project,Milestone.new] do |f| %> ... <%= f.hidden_field(:project_id, value: @project_id) %> ... <%- end -%> Or if your resource is always nested than project_id available in the params in your controller so you...

Heroku RAM not increasing with upgraded dynos

ruby-on-rails,ruby,ruby-on-rails-3,memory,heroku

That log excert is from a one off dyno, a la heroku run console - this is entirely seperate to your web dynos which you may be runnning 2x dyno's for. You need to specifiy --size=2x in your heroku run command to have the one off process use 2x dynos.

How to find a record from database by using find_by with two fields?

ruby-on-rails

If you're using Rails 4 you can do: @user = User.find_by(first_name: "John", last_name: "Doe") If rails 3: @user = User.find_by_first_name_and_last_name("John", "Doe")...

Allowing some enabled and disabled option on collection_select

ruby-on-rails,ruby

collection_select internally relies on options_from_collection_for_select helper. Rather than using the collection_select directly, you can use select and pass the result of a options_from_collection_for_select call. The reason you may want to call options_from_collection_for_select directly, is because this method also accepts an optional selected parameter that could be used to pass a...

Get X days out of an Array

ruby,ruby-on-rails-4

I would do: def get_days(wkn, *desired_days) get_week = Model.week(2) get_days_of_week = get_week.select { |x| desired_days.include? x.strftime("%A") } end ...

Rails basic auth not working properly

ruby-on-rails,ruby,authentication

@user.keys.each do |key| username == key.api_id && password == key.api_key end This piece of code returns a value of .each, which is the collection it's called on (@user.keys in this case). As it is a truthy value, the check will pass always, regardless of what are the results of evaluating...

Stack level too deep because recursion

ruby-on-rails,ruby,ruby-on-rails-4,twitter

If you express the relation properly, ActiveRecord will do it for you class Tweet belongs_to :original_tweet, class_name: Tweet has_many :retweets, class_name: Tweet, dependent: :destroy, inverse_of :original_tweet end Tweet.last.destroy # will now destroy dependents ...

Routes work in Development But not in Production

ruby-on-rails,routes

As you can see from logs, you got error page because of line 78 of app/views/shared/_header.html.erb file. In this piece of code, where you creating link <%= link_to "My Account", edit_company_path(current_user.company_id) %> Check if company_id is not nil for that particular user. I'm pretty sure it's nil in your case....

Rails Association Guidance [on hold]

ruby-on-rails,ruby,ruby-on-rails-4,ruby-on-rails-3.2

So, the complex part of your situation is that you have one thing (Surgery) that can be of many different types, and the different types have different fields. There are a number of different approaches to this problem, and I don't believe there's wide consensus on the 'best way'. The...

Same enum values for multiple columns

ruby-on-rails,ruby,enums

Maybe it makes extract the planet as another model? def Planet enum type: %w(earth mars jupiter) end class PlanetEdge < ActiveRecord::Base belongs_to :first_planet, class_name: 'Planet' belongs_to :second_planet, class_name: 'Planet' end You can create a PlanetEdge by using accepts_nested_attributes_for: class PlanetEdge < ActiveRecord::Base belongs_to :first_planet, class_name: 'Planet' belongs_to :second_planet, class_name: 'Planet'...

Split an array into slices, with groupings

arrays,ruby,enumerable

Yes, this bookkeeping with i is usually a sign there should be something better. I came up with: ar =[ { name: "foo1", location: "new york" }, { name: "foo2", location: "new york" }, { name: "foo3", location: "new york" }, { name: "bar1", location: "new york" }, { name:...

Mongoid HABTM relationships across embedded documents

ruby-on-rails,ruby-on-rails-4,mongoid,embedded-documents

The reason you are getting the error is because of the logic below. If you are going to need to represent many-to-many relations, do not use a document model to store your state. Use a relational one === You can't represent a many to many relation without an association/reference table/object....

Can Rails deal with DB uniqueness without index?

mysql,ruby-on-rails,rdbms

Because there is no need for other ways. Under the hood it's all the same: when you define a UNIQUE constraint, a UNIQUE index is created on that table to enforce it. Question from DBA.SE: When should I use a unique constraint instead of a unique index? So for a...

Get the actual value of a boolean attribute

ruby,page-object-gem,rspec3,rspec-expectations

The Page-Object gem's attribute method does not do any formatting of the attribute value. It simply returns what is returned from Selenium-WebDriver (or Watir-Webdriver). In the case of boolean attributes, this means that true or false will be returned. From the Selenium-WebDriver#attribute documentation: The following are deemed to be “boolean”...

If statement for search field in Rails

jquery,ruby-on-rails,search,if-statement

The standard way to use a search would be to include a parameter in the URL. That way you can have a similar to if user_signed_in? check for the parameter: if params[:search].present?.

For loop with flexible stop variable

ruby

Normally we'd use a loop do with a guard clause: x = 1 loop do break if x >= y x += 1 ... end Make sure y is larger than x or it'll never do anything. y can change if necessary and as long as it's greater than x...

Rails shared controller actions

ruby-on-rails,ruby,ruby-on-rails-4

You should pass actions to the included block and perform_search_on to the class_methods block. module Searchable extend ActiveSupport::Concern class_methods do def perform_search_on(klass, associations = {}) ............. end end included do def filter respond_to do |format| format.json { render 'api/search/filters.json' } end end end end When your Searchable module include a...

Ruby access words in string

ruby

What you are doing will access the fourth character of String s. Split the string to an array and then access the fourth element as follows. puts s.split[3] Note: Calling split without parameters separates the string by whitespace. Edit: Fixing indexes. The index starts from 0. That means s.split[3] will...

Heroku rake db:migrate failing - uninitialized constant

ruby-on-rails,ruby,heroku

Your migration file named should correspond to AddWeightToExercises. It should be accordingly xxxxxxxx_add_weight_to_exercises, where xxxxxxx corresponds to a particular timestamp.

What is Rack::Utils.multipart_part_limit within Rails and what function does it perform?

ruby-on-rails,ruby,rack,multipart

Telling it short, this value limits the amount of simultaneously opened files for multipart requests. To understand better what is multipart, you can see this question. The reason for this limitation is an ability to better adjust your app for your server. If you have too many files opened at...

Javascript not executing when using link_to

javascript,jquery,ruby-on-rails

This is a result of Turbolinks. You can get around this with the following: $(document).on 'click', '.my-btn', (event) -> ... This is happening because Turbolinks is loading the page, and there isn't a document ready event being fired. You want to wait until Turbolinks fires the page:load event. You do...

Rails: Posting from a form to a M:M table

ruby-on-rails,activerecord

As I said, you need to tweak your create action like this in order to save group_id. def create @group = Group.find(params[:group_id]) @discussion = current_user.discussions.build(discussion_params) @discussion.group_id = @group.id if @discussion.save flash[:success] = "Discussion started." redirect_to root_url end end OR You can add a hidden_field in your form_for to save group_id...

Keep leading zeroes when converting string to integer

ruby

Short answer: no, you cant. 2.1.5 :001 > 0001 => 1 0001 doesn't make sense at all as Integer. In the Integer world, 0001 is exactly as 1. Moreover, the number of leading integer is generally irrelevant, unless you need to pad some integer for displaying, but in this case...

Ruby- get a xml node value

ruby,xml

Try to use css instead of xpath, this will work for you, doc = Nokogiri::XML(response.body) values = doc.css('Name').select{|name| name.text}.join',' puts values => Ram,Sam ...

Ruby on Rails - Help Adding Badges to Application

ruby-on-rails,ruby,rest,activerecord,one-to-many

Take a look at merit gem. Even if you want to develop your own badge system from scratch this gem contains plenty of nice solutions you can use. https://github.com/merit-gem/merit

Ruby: How to copy the multidimensional array in new array?

ruby-on-rails,arrays,ruby,multidimensional-array

dup does not create a deep copy, it copies only the outermost object. From that docs: Produces a shallow copy of obj—the instance variables of obj are copied, but not the objects they reference. dup copies the tainted state of obj. If you are not sure how deep your object...

How to pivot array into another array in Ruby

arrays,ruby,csv

Here is a way using an intermediate hash-of-hash The h ends up looking like this {"Alaska"=>{"Rain"=>"3", "Snow"=>"4"}, "Alabama"=>{"Snow"=>"2", "Hail"=>"1"}} myArray = [["Alaska","Rain","3"],["Alaska","Snow","4"],["Alabama","Snow","2"],["Alabama","Hail","1"]] myFields = ["Snow","Rain","Hail"] h = Hash.new{|h, k| h[k] = {}} myArray.each{|i, j, k| h[i][j] = k } p [["State"] + myFields] + h.map{|k, v| [k] + v.values_at(*myFields)} output...

Make instance variable accessible through hash in Ruby

ruby-on-rails,ruby,ruby-on-rails-4,activerecord

It's not "through Hash", it's "array access" operator. To implement it, you need to define methods: def [](*keys) # Define here end def []=(*keys, value) # Define here end Of course, if you won't be using multiple keys to access an element, you're fine with using just key instead of...

Is it possible to have two callbacks in around_destroy in rails?

ruby-on-rails,activerecord,callback

It'll work without any issue, as Active Record wraps-up these callback methods in a single transaction. Since the object is destroyed in first yield, it seems the later is not feasible (assuming everything is running in one thread). How Rails handles this? No, object isn't destroyed in first yield. Object...

On rendering from controller, current_page method does not seem to work

ruby-on-rails,ruby,ruby-on-rails-4,model-view-controller

You can use content_for and yields to create a default in your layout which views can override. # layouts/application.html.erb: <% if content_for?(:banner) %> <%= yield(:banner) %> <% else %> <div id="banner"> <h1>This is the default...</h1> </div> <% end %> /users/signup.html.erb: <%- content_for :banner, flush: true do -%> <!-- move along,...

Active Record association links, but can't assign values

ruby-on-rails

Your column should be permission_id, not permissions_id. That is why AR doesn't find the related model.