2017-06-16 58 views
1

我是Rails的新手,並且希望創建一個模型,其中每個post#show進入引導模式時不會進入單獨的show.html.erb頁面。當你有佈局時如何獲得@post的params [:id]:false

在我show方法我有這樣的事情:

def show 
    @confessions = Confession.find(params[:id]) 
    @comment = Confessioncomment.where(confession_id: @confessions).paginate(page: params[:page], per_page: 5).order('created_at ASC') 
end 

我讓我的@confessionsparams[:id]截至目前,以顯示確切的文章中,我點擊了,但我想是不是表現出單獨的顯示頁面,但在同一頁面上加載我的引導模式中的所有內容。

我知道我可以使用layout :false來告訴show不會有佈局,但我不知道如何使用它,或者如果有任何其他方式來做到這一點。

如何在同一頁面顯示帖子,而不是從控制器加載新頁面。

任何想法?

回答

2

請勿通過導軌視圖渲染器加載它。取而代之的是,從你的JavaScript代碼中並加載引導模式之前做一個AJAX調用打端點/路由拉記錄,但返回它的JSON:

def show 
    @confessions = Confession.find(params[:id]) 
    @comment = Confessioncomment.where(confession_id: @confessions).paginate(page: params[:page], per_page: 5).order('created_at ASC') 

    render json: @confessions, status: 200 
end 

然後用你的JS是JSON響應動態加載模態。

您可能還希望僅返回一個供認實例模型,並從其關係中提取註釋,如@confession.comments,但您需要正確設置模型。這將使你的渲染比使用兩個不同的實例變量更容易。

+0

感謝建議...我會嘗試這個,看看它是否工作.. :) –

+0

你能幫我一個忙嗎?你能解釋我怎麼能用我的javascript代碼返回的JSON來創建@confessions返回的數據的視圖.. 這將是一個很好的幫助..謝謝 –

+0

@AlaapDhall以及你可以像使用jQuery + Bootstrap動態建立模態,然後捕捉成功處理程序。嘗試在這裏搜索stackoverflow的例子,應該有很多。祝你好運! –

0

首先,佈局假的不是你在想什麼......

Rails的一些默認的行爲作品。即使您的控制器中沒有方法定義,應用程序的每條路徑也會調用具有相同名稱的視圖。

如果您不想使用任何方法呈現其他模板,則必須在其末尾調用渲染函數。

def show 
    @confessions = Confession.find(params[:id]) 
    @comment = Confessioncomment.where(confession_id: @confessions).paginate(page: params[:page], per_page: 5).order('created_at ASC') 
    render 'another/page', layout: false 
end 

我告訴Rails該代碼是從佈局爲false的路徑'another/page'呈現模板。

現在我告訴你什麼是佈局錯誤。

您的全新項目帶有一個application.htlm.erb佈局,可以生成應用程序的每個其他頁面。有時你不希望頁面被佈局取消,所以你應用layout false或佈局:'another/layout'。

在供述列表
1

/表

<%= link_to @confession.title, @confession, remote: true %> 

在控制器

def show 
    @confessions = Confession.find(params[:id]) 
    @comment = Confessioncomment.where(confession_id: @confessions).paginate(page: params[:page], per_page: 5).order('created_at ASC') 

    respond_to do |format| 
    format.html 
    format.js 
    end 
end 

創建一個文件show.js.ERB具有以下內容

$('#dynamically_filled').find('.modal-dialog:first').html("<%=j render('confession') %>"); 
$('#dynamically_filled').modal(); 

在show.html.erb的頂部添加此

<div class="modal fade" tabindex="-1" role="dialog"> 
    <div class="modal-dialog" role="document"> 

    </div><!-- /.modal-dialog --> 
</div><!-- /.modal --> 

_confession.html.erb必須上下文的內容,其餘

<div class="modal-content"> 
    <div class="modal-header"> 
    <button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">&times;</span></button> 
    <h4 class="modal-title"><%= @confession.title %></h4> 
    </div> 
    <div class="modal-body"> 
    <p><%= @confession.content %></p> 
    </div> 
</div><!-- /.modal-content -->