Menu
  • HOME
  • TAGS

use multiple virtual attribute form inputs to update a single model attribute

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

I have the following virtual attributes within my model:

attr_accessor :city, :zip, :street, :suite

In the new/edit form, I have form fields for each of these attributes. I can convert these four attributes into a single address_id with a method we'll call address_lookup. I only need to store the address_id in the model. What's the basic approach to cleanly handle this in the create/update controller actions, and (if necessary) the model? It's a little over my head.

Best How To :

Simplest is to add in a before_save callback, we'll use the changed array to check whether any of the attributes we're interested in have changed before we do our lookup:

before_save :set_address

def set_address
  if address = Address.find_or_create_by( city: city, zip: zip, street: street, suite: suite)
    self.address = address
  end
end

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...

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...

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...

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

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,...

User.id not getting saved in form

ruby-on-rails

When you are using nested routes you need to get the parent id from the parameters and merge it with the form parameters. When you post the form the parameters look something like this: { user_id: 1, promo: { title: "¡Ay, caramba!" } } Doing params.require(:promo)... slices the params hash...

Sorting in Ruby on rails

ruby-on-rails,json,sorting

You're not getting the results you want because you're not assigning the sorted user_infos back into the user_infos variable. You can do the following: user_infos = user_infos.sort {|a, b| - (a['can_go'] <=> b['can_go']) } # -or- user_infos.sort! {|a, b| - (a['can_go'] <=> b['can_go']) } The first version of sort creates...

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....

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,...

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.

In Ruby how to put multiple lines in one guard clause?

ruby-on-rails,ruby

Don't know what the surrounding code looks like so let's assume your code is the entire body of a method. Then a guard clause might look like this: def some_method return if params[:"available_#{district.id}"] != 'true' @deliverycharge = @product.deliverycharges.create!(districtrate_id: district.id) delivery_custom_price(district) end ...

Rails: get f.range_field to submit null or nil as default value

ruby-on-rails,forms

You can just add a hidden checkbox value to judge whether user select or not. = f.range_field :content, :value=> nil, :class=> "question-field percentage", :step => 10, :in => 0..101, :data => {:question => question.id = check_box_tag :range_clicked, true, false, style:'display:none;' and then add a js function to tell whether user...

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")...

Rails Generates Blank Record Even Input Data

ruby-on-rails,crud

Strong parameters Rails sends form parameters in nested hashes. { page: { subject_id: 1, name: 'Hello World.' } } So to whitelist the parameters you would do. class PagesController < ApplicationController def index @test = Page.all end def new @test = Page.new end def create @test = Page.new(page_params) if @test.save...

Entering data into mysql database using php

php,mysql,forms,mamp

This shoud work, if not then check your usename and password... <?php $servername = "localhost"; $username = ""; $password = ""; $dbname = "first_db"; $pathway = $_POST['username']; username - is the name of your input. // Create connection $conn = mysqli_connect($servername, $username, $password, $dbname); // Check connection if (!$conn) {...

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 ...

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.

Run AJAX function on form submit button after javascript confirm() cancel

javascript,jquery,ajax,wordpress,forms

Dont use one(it will fire ajax submit or button click only once) , use here var IsBusy to check user is not repeatedly pressing the form submit, Try below code, var isBusy = false; //first time, busy state is false $('#publish').on('click', function (e) { if(isBusy == true) return ; //if...

Angular submit not called when required fields not filled

javascript,angularjs,forms

You need to add novalidate to your form. The reason being, your browser is validating your form rather than letting your code do it. alternatively, do something like: <form ng-submit="submit()" name="form" novalidate> <ion-radio ng-repeat="item in items" ng-model="data.type" name="type" ng-value="item.value" ng-class="{'error' : form.type.$invalid && form.$submitted }" </form> form.$submitted will become true...

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 ...

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 ...

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 - link_to path based on object's name + refactoring multiple custom actions

ruby-on-rails,ruby,refactoring

You can change your routes : resources :techs, :only => [:index, :show], shallow: true do resources :cars, only: [:new, :create] collection do get 'part/:part_name' => "techs#part", as: :part end end Then add the action : def part @techs = Tech.joins(:services).where(services: { name: params[:part_name]}) end and the view will be :...

rendering the partials in controller after the validation check

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

Why this is not working? if params[:user][:user_role] render :partial => 'users/mentor' else render :partial => 'users/mentee' end params[:user][:user_role] is nil. You can check it using lots of way: Above your if condition raise params[:user].inspect Why its nil? Reason of this is You are passing new_user_path(user_role: true) user_role true, but user_role...

Symfony 2 unable to pass entity repository to form

php,forms,symfony2,runtime-error

You have not included the Symfony EnityRepository class at the top of your form file so PHP is looking for it in the same directory as your form class. Hence the error message. Add this to your form class (or qualify EntityRepository inline): use Doctrine\ORM\EntityRepository; ...

Seeding fails validation for nested tables (validates_presence_of)

ruby-on-rails,ruby,validation,ruby-on-rails-4,associations

Found this : Validating nested association in Rails (last chapter) class User belongs_to :organization, inverse_of: :users validates_presence_of :organization_id, :unless => 'usertype==1' end class Organization has_many :users accepts_nested_attributes_for :users, :reject_if => :all_blank, :allow_destroy => true end The documentation is not quite clear about it but I think it's worth a try....

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...

Can't map a range of dates in Ruby/Rails

ruby-on-rails,ruby

You can try : dateLabels = <%= raw @mapped_dates.as_json %>; This will return ["Jan 1", "Jan 2", "Jan 3", ... ] For ActiveSupport::TimeWithZone problem, please do - In config/initializers/time_zone.rb class ActiveSupport::TimeWithZone def as_json(options = {}) if ActiveSupport::JSON::Encoding.use_standard_json_time_format xmlschema else %(#{time.strftime("%Y/%m/%d %H:%M:%S")} #{formatted_offset(false)}) end end end ...

Show only the requested forms using JS

javascript,jquery,html,html5,forms

Keep both the forms hidden at first and give a ID to each <a> and also to the <form> Then $("#id-of-btn1").click(function(){ $("#form-1").toggle(); }); and $("#id-of-btn2").click(function(){ $("#form-2").toggle(); }); EDIT: This could be a solution to make it completely independent of ID/Classes. If you give a class to div containing all the...

Getting a collection via Ajax to show in view

jquery,ruby-on-rails,ajax

Your partial (currently named: _followup.html.erb in your example) should just be the code to produce a single row, Rails will iterate over it for you, and you should name it after the model it represents, ie. # app/views/assessments/_assessment.html.erb <%= assessment.name %> Then in your app/views/assessments/followups.html.erb view you'd use that partial...

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.

paper clip show image url is undefine

ruby-on-rails

So your @result is a collection of users. Just call <%= r.image.url(:medium) %>

Broken Rails integration after moving 'micropost feed' - Expected at least 1 element matching “div#error_explanation”, found 0

ruby-on-rails,integration-testing

If you look at the error First argument in form cannot contain nil or be empty You can clearly make out from it that the first argument that's @micropost variable is nil. Now move to the controller and see if you have set that variable or not. In else part...

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'...

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?.

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...

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...

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...

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...

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...

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...

Rails - Simple Form - Nested Resources paths

ruby-on-rails,simple-form,simple-form-for

Your new action of project_answers controller should be having @project, @project_question defined def new @project_answer = ProjectAnswer.new @project = Project.find(params[:project_id]) @project_question = ProjectQuestion.find(params[:project_question_id]) end So that you can use those in the form like this <%= simple_form_for [@project, @project_question, @project_answer] do |f| %> ...

Rspec view test with url parameters

ruby-on-rails,unit-testing,testing,rspec,rspec-rails

Because these are redirects, controller testing with render_views will not work. Nope, you are just doing it wrong. If StaticpagesController#dashboard accepts url parameters you should test how it responds to said parameters in the controller spec for StaticpagesController. RSpec.describe StaticpagesController, type: :controller do describe 'GET #dashboard' do render_views it...

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...

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 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...

Active Record Where Clause For Relation In Model

ruby-on-rails,activerecord

I want to select sites of premium user This will do User.includes(:sites).where('users.category = ?', 'premium') Update If sites also have categories like 'wordpress or joomla', how do i apply where clause to select only wordpress sites of premium users For that you need to tweak the query like this...

Redirect if ActiveRecord::RecordNotUnique error exists

ruby-on-rails,postgresql,activerecord,error-handling

Just the way you catch every other error begin Transaction.create!(:status => params[:st], :transaction_id => params[:tx], :purchased_at => Time.now) rescue ActiveRecord::RecordNotUnique redirect_to root_path end ...

Rails less url path change

ruby-on-rails,ruby,url,path,less

You should use the font_url, and put the font in app/assets/fonts @font-face { font-family: 'SomeFont'; src: font_url("db92e416-da16-4ae2-a4c9-378dc24b7952.eot?#iefix"); //... } ...