简体   繁体   中英

How do I display only “Specific” project(s) on a separate View Page in Rails?

On my index.html.erb page I have a list of all my projects @projects = Project.order() and have written code to determine if the project(s) are "dueSoon" or "Late" and added Styles. Now I have created a 2nd View Page called "Delinquent" where I want to display only the project(s) that are either late or duesoon. I am trying to figure out the best/cleanest way to display this. Here is my code from my index View:

<table class....
...
<% @projects.each do |project| %>
<% colorClass = project.late? ? "late" : project.dueSoon? ? "dueSoon" : "ok" %>
 <tr>
   <td class=<%= colorClass %>><%= link_to project.product, project %></td>
 ....
 ...

Now I know I want my logic to be something like IF (project) = late OR duesoon then true (Display project(s). I am just not 100% sure the best way to code this.

Thank You.

I looked at the Active Record Querying link you attached. I was looking at the Scope section 14.2 Merging of Scopes. Looks like I could do something like this:

class Project < ActiveRecord::Base
 scope :late, -> { where(late: true) }
 scope :duesoon, -> { where(duesoon: true) }
 end 

Then I it looks like I can merge them by doing Projects.late.duesoon

Please let me know if this logic looks somewhat accurate. Thanks

One approach would be to add a delinquent class method to Project.

Something like this in your model:

class Project               
  def self.delinquent
    where(delinquent: true)
  end
end

Then something like this in your view:

<% @projects.delinquent.each do |project| %>

Another approach is to define a scope in your project model:

class Project < ActiveRecord::Base
  scope :displayable, where(:displayable => true)
  ...
end

From the Rails Guides: "Scoping allows you to specify commonly-used queries which can be referenced as method calls on the association objects or models. With these scopes, you can use every method previously covered such as where, joins and includes. All scope methods will return an ActiveRecord::Relation object which will allow for further methods (such as other scopes) to be called on it."

http://guides.rubyonrails.org/active_record_querying.html

In your model / controller code, you can then use

 Project.displayable

to fire the query.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM