logo
down
shadow

How to refactor this Model logic in Rails


How to refactor this Model logic in Rails

By : user2955185
Date : November 22 2020, 10:38 AM
hop of those help? Assuming that a teacher has_many students and a student belongs_to a teacher, you could to the following:
Teacher.rb
code :
has_many :students, inverse_of: :teacher

def self.get_students_report
  self.includes(student: :subjects).map(&:students_reports).flatten
end

def students_reports
  students.map(&:record).flatten
end
belongs_to :teacher, inverse_of: :students

def record
  {
    student_name: name,
    teacher_name: teacher.name,
    attendance: attendance, 
    subject_total: subject_total,
    subject_percentage: mark_in_percentage
  }
end

private

def attendance
  (student.days_attended/classes_taken.to_f) * 100.0
end

def classes_taken
  teacher.classes_count
end

def subject_total
  subjects.sum(:marks_obtained)
end

def mark_in_percentage
  (subject_total * 100)/subjects.sum(:maximum_mark).to_f
end


Share : facebook icon twitter icon
Rails partial overloaded with logic needs refactor

Rails partial overloaded with logic needs refactor


By : Nisha
Date : March 29 2020, 07:55 AM
Does that help I don't know if I want to wade my way through that but I'll get you started.
code :
<%- if post.name.empty? -%>
<%- else -%>   
  <span class="name">
    by 
    <%- if post.email.blank? -%>
      <%= post.name %>
    <%- else -%>
      <a href="mailto:<%= post.email %>"><%= post.name %></a>
    <%- end -%>
  </span>
<%- end -%>
<%= by_post_name post %>

#post_helper.rb
def by_post_name post
  post.name.empty? ? "" : "<span>#{post.email.blank? ? post.name : mail_to post.email, post.name}</span>"
end
<%- if post.comments.empty? -%>
  <span class="reply">
    <%= link_to 'reply', :controller => 'posts', :action => 'show', :id => post %>
  </span>
<% else %>
  <span class="reply">
    <%= link_to pluralize(post.comments.count, 'reply'), :controller => 'posts', :action => 'show', :id => post %>
  </span>
<%- end -%>
<span class="reply">
  <%- if post.comments.empty? -%>
    <%= link_to 'reply', :controller => 'posts', :action => 'show', :id => post %>
  <% else %>
    <%= link_to pluralize(post.comments.count, 'reply'), :controller => 'posts', :action => 'show', :id => post %>   
  <%- end -%>
</span>
Refactor Rails 3 views - move logic to <model>_helper

Refactor Rails 3 views - move logic to <model>_helper


By : AMascorro
Date : March 29 2020, 07:55 AM
help you fix your problem I would like move the following from my View into the model's associated helper: , You can do it even better:
code :
def posted_filters(*args)
  args.collect { |bucket|
    link_to_unless(params[:posted]==bucket, bucket, jobs_path(:posted =>bucket, :starting=>params[:starting],:sort=>params[:sort],:dir=>params[:dir]))
  }.join(' | ').html_safe
end
[ <%= posted_filters(0, 30, 60, 90) %> ]
What is the best way to refactor validation logic and regular expressions in rails?

What is the best way to refactor validation logic and regular expressions in rails?


By : rd888
Date : March 29 2020, 07:55 AM
seems to work fine Build custom validators for the various types of validations you need, then invoke them in your model classes.
For example:
code :
class PostalCodeValidator < ActiveModel::EachValidator
  def validate_each(record, attr_name, value)
    unless value =~ /^\d{5}$/
      record.errors[attr_name] << "must be a 5-digit postal code"
    end
  end
class Customer < ActiveRecord::Base
  validates :postal_code, :postal_code => true
end
Refactor ruby on rails model

Refactor ruby on rails model


By : Kannan
Date : March 29 2020, 07:55 AM
this will help If you need additional context, pass it through as an additional argument. That's how it's supposed to work.
Setting @-type instance variables to pass context is bad form as you've identified.
code :
KEYWORDS = { 
    :C => ['cause', 'causes'],
    :I => ['prevent', 'inhibitors'],
    :P => ['type','supersets'],
    :E => ['effect', 'effects'],
    :R => ['reduce', 'inhibited'],
    :S => ['example', 'subsets'] 
}

def search_type_of_relation_in_text(issue_id, type_of_causality)
  KEYWORDS[type_of_causality.to_sym].collect do |keyword|
    search_word(keyword, relation_type, issue_id)
  end
end

def search_word(keyword, relation_type, issue_id)
  relation_occurrences = [ ]

  @buffer.search(%Q{//p[text()*= "#{keyword}'"]/a}).each do |relation|
    relation_suggestion_url = "http://en.wikipedia.org#{relation.attributes['href']}"
    relation_suggestion_title = URI.unescape(relation.attributes['href'].gsub("_" , " ").gsub(/[\w\W]*\/wiki\//, ""))

    if (!@current_suggested[relation_type].include?(relation_suggestion_url))
      occurrence = {
        :title => relation_suggestion_title,
        :wiki_url => relation_suggestion_url,
        :causality => type_of_causality,
        :issue_id => issue_id
      }

      occurrence[:status] =
        if (@accepted[relation_type].include?(relation_suggestion_url))
          'A'
        else
          'N'
        end

      relation_ocurrences << occurrence
    end
  end 

  relation_occurrences
end
How to refactor complex search logic in a Rails model

How to refactor complex search logic in a Rails model


By : Ajay005
Date : March 29 2020, 07:55 AM
I wish this helpful for you For starters, "Grab all discussions based on category and/or filter" can be a separate method.
params[:filter] is repeated many times, so take that out at the top:
code :
filter = params[:filter]
if [:hot, :new, :top].incude? filter
  discussions = discussions.open.send "order_by_#{filter}"
...
def do_something
  return 'foo' if ...
  return 'bar' if ...
  'baz'
end
def evaluate_something
  if a==1
    return 'foo'
  elsif b==2
    return 'bar'
  else
    return 'baz'
  end
end
def evaluate_something
  return 'foo' if a==1
  return 'bar' if b==2
  'baz'
end
Related Posts Related Posts :
  • Why "bundle install" try to install outdated version of gems?
  • Rails - Customize model validation error messages but without a database
  • When to switch from cucumber to rspec in the BDD cycle for a login procedure
  • Multipart response for web service
  • How to hide Add new option in Rails Admin
  • Override CollectionProxy find method
  • Rails 4 simple_form has_many through check boxes not saving
  • ruby on rails authentication using devise gem
  • Rails iteration over arrays and hashes
  • Creating inline date_select dropdowns using simple_form and zurb foundation
  • NameError in SongsController#index uninitialized constant Song::FriendlyId
  • Rails how to improve if record exists?
  • omniauth custom request phase form
  • Rails 5 - Saving the absolute current url via a button to a cookie?
  • How can / should I override the `build` method for a my model?
  • Install Rails Failed on OSX 10.8.4
  • ruby on rails - undefined method valid?
  • Users Registration on POST
  • Rails application variables in carrierwave store_dir
  • How to customize simple_form for json nested hash
  • Couldn't find file 'jquery', Sprockets::FileNotFound in StaticPages#home error
  • How should I use the alias_method_chain for the build method?
  • how to create two custom registration forms in devise?
  • Rails 4 link_to Destroy not working in Getting Started tutorial
  • How does ruby on rails dynamically define `find_by_id`, `find_by_name` methods?
  • JBuilder dynamic keys for model attributes
  • `initialize': No such file or directory - getaddrinfo (Errno::ENOENT) when Rails new app
  • What is the Ruby equivalent of Node.js' socket.io?
  • Where rails store standard helpers?
  • how to check expected result matches any of give values in rspec?
  • Form submission to create multiple objects
  • Simple Twitter Login with Rails and Email confirmation
  • Where should helpful functions for my controller go in Rails?
  • Using session variable in the Model or the other way
  • Why can't I have ruby code and comments in Embedded Ruby?
  • Rails: How can I make an object available in all views?
  • Cannot enter simply form information into SQLite DB (Rails)
  • Rails - Retain form values on failed submission. Getting "First argument in form cannot contain nil or be empty&quo
  • How to handle STI and build related models automatically?
  • Suppress an error when saving a record in Rails
  • Rails AJAX reload the page. Why?
  • How to pass user attributes to action mailer
  • Custom Validator to Prevent an appointment from being scheduled too early in day?
  • Postgres Enable TCP/IP Connection
  • How do I avoid the circular argument reference warning in activesupport
  • Unable to push to heroku master because of rails/spring version error
  • deep nested routes in rails
  • Best approach to Users Profile Images in Rails App
  • RailsInstaller: Can I maintain the gem fold when re-installing a new version?
  • couldn't find file 'jquery-ui' i get this error even after having this file in my application.js
  • Ruby regex to split user and date text input
  • Tool like BetterErrors for JRuby?
  • redirect_to in action destroy ruby on rails
  • Where are the I18n.t link and reference paths?
  • Sending emails to multiple recipients in rails app
  • Rails, Devise, Sign up = write name in other Database
  • pass custom attribute on rspec factory_girl controller test
  • rails generate uses wrong version of Ruby
  • Duplicate Requests from a Browser
  • One action in Rails controller sends no data back
  • shadow
    Privacy Policy - Terms - Contact Us © ourworld-yourmove.org