1

I'll start by saying that I'm new to rails. This question is for a class I'm currently taking. The lesson topic is CRUD, and the content is a db that stores posts along with their titles and comments.

The instructions are as follows:

Overwrite the title of every fifth instance of Post with the text "CENSORED".

This is my controller:

class PostsController < ApplicationController

  def index

  @posts = Post.all
  end

  def show
  end

  def new
  end

  def edit
  end
end

This is my view file:

<h1>All Posts</h1>

<% @posts.each do |post| %>

    <div class="media">
      <div class="media-body">
        <h4 class="media-heading">
          <%= link_to post.title, post %>
        </h4>
      </div>
    </div>
<% end %>

This is my model:

class Post < ActiveRecord::Base
  has_many :comments
end

I'm not really sure where to even start and would really appreciate any help at all. A point in the right direction would be great. Thanks.

JonMalis
  • 13
  • 5

5 Answers5

1
@posts = Post.all
@posts.each_with_index do |post, index| 
  if index % 5 == 4 # since index starts at 0, every 5th object will be at positions 4, 9, 14, 19 etc.
    # Do the change on post object
    post.update_attributes(title: 'CENSORED')
  end
end
Rajesh Omanakuttan
  • 6,788
  • 7
  • 47
  • 85
  • Thanks a lot @Rajesh Omanakuttan! I was trying `if post % 5`... This makes sense and works perfectly. – JonMalis Aug 24 '15 at 16:30
1

Here are a couple of ways, where @posts = Post.all, and assuming the first post is to be censored:

#1

e = [[:CENSOR] + [:PUBLISH]*4].cycle
  #=> #<Enumerator: [[:CENSOR, :PUBLISH, :PUBLISH, :PUBLISH, :PUBLISH]]:cycle>    
@posts.each {|p| p.update_attributes(title: 'CENSORED') if e.next==:CENSOR }

#2

(0...@posts.size).step(5) {|i| @posts[i].update_attributes(title: 'CENSORED')}
Cary Swoveland
  • 106,649
  • 6
  • 63
  • 100
0

Use each_with_index instead of each; if the index modulo 5 is zero, censor it.

Amadan
  • 191,408
  • 23
  • 240
  • 301
  • 1
    `index % 5 == 0` will yield unexpected results. In particular, the first item will be censored too. – Sergio Tulentsev Aug 24 '15 at 06:13
  • @SergioTulentsev: Not unexpected to me. OP just said every fifth, without specifying which one should be the first censored one. Also, it is trivial to offset, and OP should be able to deduce how. (Actually, someone already posted it, so...) – Amadan Aug 24 '15 at 06:17
0

If the intent is to display "CENSORED" for every fifth element, then I'd take a look at each_with_index: http://apidock.com/ruby/Enumerable/each_with_index

kevinthompson
  • 574
  • 3
  • 15
0

If @posts is in array form

@posts.each_with_index do |post,index|
  post.update!(title: "CENSORED") if index % 5 == 0
end

OR

If @posts is in your database

@posts.each do |post|
  post.update!(title: "CENSORED") if (post.id % 5 == 0)
end
tomtom
  • 1,130
  • 2
  • 11
  • 35