簡體   English   中英

Rails 3.1.3使用anchor屬性和posts_to標簽從posts / index到posts / show / id不起作用

[英]Rails 3.1.3 using anchor attribute with link_to tag from posts/index to posts/show/id not working

我在我的帖子/索引視圖上使用了link_to標簽,並希望將其鏈接到我的帖子/ show / id視圖,並使用一個錨點向下滾動到評論表單。 出於某種原因,我無法讓錨點工作。 這是我的代碼:

在帖子/索引中

<%= link_to 'Add a Comment', post, :anchor => 'comment_form' %>

這無法將#符號附加到鏈接的末尾,因此它只是localhost:3000 / posts / id。 我也為link_to嘗試過很多變種,包括:

<%= link_to 'Add a Comment', post(:anchor => 'comment_form' %>

<%= link_to 'Add a Comment', :controller => 'posts', :action => 'show', :id => @post, :anchor => 'comment_form' %>

但我沒有運氣。

這是我的帖子#show action:

  def show
    @post = Post.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @post }
    end
  end

這里是我希望錨點滾動到的帖子/顯示視圖:

<h2><a name="comment_form" id="comment_form">Add a comment:</a></h2>

此外,如果我鏈接到索引頁面上的某些內容,上面的任何一個都可以工作,因為我可以看到散列#已被附加到輸出的url。 由於某種原因,在嘗試鏈接到節目頁面時它無法正常工作。 對此有何幫助?

嘗試這個:

link_to('Add a comment', post_path(post, :anchor => 'comment_form'))

link_to的第二個參數通常按原樣傳遞給url_for ,第三個參數用作最終生成的<a>元素的屬性哈希。

因此,在您的第一個示例中,您將Post對象作為第二個參數傳遞,並將散列作為第三個參數傳遞。 只有Post會被傳遞給url_for 它永遠不會看到包含:anchor選項的哈希,因此您不會在生成的URL的末尾看到錨點。 (但你可能會在生成的<a>元素上看到一個anchor="comment_form"屬性。)

你的第二個例子在語法上是不正確的。 我想這導致了一個錯誤。

你的第三個例子......應該有效。 我不確定為什么沒有:-)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM