2012-10-17 4 views
0

내 데이터베이스에 "startDate"이라는 열이 있습니다. 저장된 startDate의 예는 2000-01-01 12 : 01 : 01.000000입니다. (이 날짜는 Created_at 또는 modified_at 날짜와 다릅니다.이보기의 show.html.erb에 언급 된 이벤트의 날짜가됩니다.)텍스트 검색 매개 변수가 Rails에 전달 된 결과 페이지로 연결

기사보기보기에서 링크를하고 싶습니다. 비슷한 마이크로 포스트가 표시 될 결과 (색인) 페이지로 이동합니다. 어떻게해야할지 모르겠습니다.

There are 17 events within 10 days before or after the date Wednesday October 17th, 2009.

단어 "17 개 이벤트"결과 페이지에 링크 될 것이다 :

링크 텍스트는 무언가 같이 말할 수 있습니다. 이 특정 예에서 검색의 범위는 수요일 10 월 17 일, 2009십일와 총 이십일 및 후 십일 될 것이다.

이것은 현재 나의 show.html.erb 페이지입니다.

<div class="row"> 
    <div class="span2"><center><img src=<%= @micropost.imageURL %> class="img-polaroid"></center></div> 

    <div class="span7"> 
     <h3><%= @micropost.title %></h3><br> 
     <p><small><%= @micropost.loc1T %><br> 
      <%= @micropost.startTime.strftime('%A, %B %d, %Y') %></small></p> 
     <p><%= raw @micropost.content %></p> 
    </div> 

    <div class="span3"><img src="http://placehold.it/210x210" class="img-polaroid"><br> 
    <small>advertisment</small> 
    <div class="divider">&nbsp;</div> 
    <div class="well"> 

    <p>There are <%= link_to(pluralize("event", @microposts.count), "#{microposts_path} related=#{@micropost.id}") %> within 10 days...</p> 


    </div> 

    </div> 
</div> 

모델/micropost.rb

class Micropost < ActiveRecord::Base 
    attr_accessible :content, :title,:keyword,:privacy,:groups,:loc1T,:latitude,:longitude,:loc2T,:loc2Lat,:loc2Lon,:startTime,:endTime,:imageURL 
    geocoded_by :loc1T 
    after_validation :geocode#, :if => :address_changed? 


    belongs_to :user 

    validates :user_id, presence: true 
    validates :title, presence: true 
    validates :keyword, presence: true 
    validates :privacy, presence: true 
    validates :groups, presence: true 
    validates :loc1T, presence: true 
    validates :latitude, presence: true 
    validates :longitude, presence: true 
    validates :loc2T, presence: true 
    validates :loc2Lat, presence: true 
    validates :loc2Lon, presence: true 
    validates :startTime, presence: true 
    validates :endTime, presence: true 
    validates :imageURL, presence: true 

    validates :content, presence: true 

    default_scope order: 'microposts.created_at DESC' 

    def self.from_users_followed_by(user) 
    followed_user_ids = "SELECT followed_id FROM relationships 
         WHERE follower_id = :user_id" 
    where("user_id IN (#{followed_user_ids}) OR user_id = :user_id", 
      user_id: user.id) 
    end 

    def related_microposts(this_startTime) 
    @microposts.where('startTime > ? AND startTime < ?', 5.days.since(startTime), 5.days.until(startTime)) 
    end 
end 

microposts_controller.rb

class MicropostsController < ApplicationController 
    before_filter :signed_in_user, only: [:create, :destroy] 
    before_filter :correct_user, only: :destroy 

    def index 
    end 

    def show 
    @micropost = Micropost.find(params[:id]) 
    end 

    def related_microposts(this_startDdate) 
    Micropost.where('startDate > ? AND startDate < ?', 5.days.since(this_startDate), 5.days.until(this_startDate)) 
    end 

    def create 
    @micropost = current_user.microposts.build(params[:micropost]) 
    if @micropost.save 
     flash[:success] = "Micropost created!" 
     redirect_to root_url 
    else 
     @feed_items = [] 
     render 'static_pages/home' 
    end 
    end 

    def destroy 
    @micropost.destroy 
    redirect_to root_url 
    end 

    private 

    def correct_user 
     @micropost = current_user.microposts.find_by_id(params[:id]) 
     redirect_to root_url if @micropost.nil? 
    end 
end 

이 데이터베이스 컬럼의 스크린 샷입니다 ...

DB Screenshot

답변

0

S 해결할 몇 가지 문제가있는 것처럼 ounds.

기사 start_date 기사의 5 일 내에 목록을 가져올,

첫째 (다음 레일 규칙은, 당신의 열을 가정하기 위하여려고하고 정말 start_date :-)라고 함), 당신이 뭔가를 사용할 수 있습니다 like

def related_articles(this_start_date) 
    Article.where('start_date > ? AND start_date < ?', 5.days.since(this_start_date), 5.days.until(this_start_date)) 
end 

시간 기능이 잘못되었을 수 있지만 check here for details 일 수 있습니다.

이제 related_articles에 필요한 것이 있습니다. 카운트 만 필요한 경우 related_articles.count으로 가져 오거나 @articles으로 저장할 수 있습니다. 현재 @article 표시하는 메인 페이지에서 이제 모든 기사를 목록으로 당신의 index보기의 경로입니다

There are <%= link_to(pluralize("event", @articles.count), "#{articles_path}?related=#{@article.id}") %> within 10 days... 

articles_path처럼, 관련 기사를 표시 할 수있는 링크를 추가 단지 나열하는 컨트롤러의 index 방법에 일부 코드를 넣어 특수 쿼리 문자열 매개 변수가있는 경우 해당 기사

if params[:related] 
    this_article = Article.find params[:related] # 123 is the id of the main article 
    @articles = Article.related_articles(this_article) 
else 
    @articles = Article.all 
end 

비조직적 대답의 종류,하지만 난 그게

+0

:-) 주요 지점에서 얻을 생각은 내가 내 게시물에서 단어 "제품"을 사용하여 당신을 던진 것 같아요. 내 게시물에있는 모든 것은 "microposts"라는 db에 관련됩니다. 나는 당신의 코드를 시험해 보았고 "article"이라는 단어를 "micropost"로 대체했습니다. 귀하의 첫 번째 코드 블록이 ** microposts_controller.rb **에 들어가고 ** 두 번째 코드가 ** show.html.erb **로 들어간 것으로 가정합니다. ** 나는 원래의 게시물을 내가 시도한 것으로 업데이트했습니다. 결국 오류 메시지가 나타납니다 : 정의되지 않은 메서드 'count'for nil : NilClass. 아, 그리고 칼럼의 이름을 "startDate"로 했어. 나는 초보자입니다. – Livi17

+0

새내기 환영합니다. 저는 하나이기도하고 2007 년부터 Rails를 해왔습니다.하지만 제가 게시 한 코드는 여러분이해야 할 일의 일반적인 요지에 불과합니다. 첫 번째 블록'def related_articles ...'는'micropost.rb' 모델에 들어갑니다. 두 번째 줄 ("<% = link_to ...")이보기 ('show.html.erb')에 나타납니다. 마지막은 컨트롤러에 들어갑니다. 나의 충고는 문제를 청크로 분해하는 것이다. development.log 파일을 보면 사이트의 어떤 페이지 (특히 path 및 params 배열)로 이동할 때 어떤 결과를 얻을 수 있는지 확인할 수 있습니다. –

+0

다시 도움 주셔서 감사합니다. 시간이 지나면 더 쉬워지기를 바랍니다. 나는 당신의 솔루션을 다시 시도했다. 그러나 show.html.erb에서 다음과 같은 오류가 발생한다 :'undefined method 'count for'for nil : NilClass' : **

<% = link_to (pluralize (" 이벤트 ", @ microposts.count),"#{microposts_path}?related=#{@micropost.id} ") %> 10 일 이내 ...

**. 내 microposts_controller.rb에 누락 된 것이 있습니까? – Livi17

관련 문제