2015-04-26 52 views
0

我有一個公告'has_many'評論和評論'belongs_to'公告關係。 在我的根目錄中,我在每個循環中顯示公告,並且我嘗試在每個新聞下發表評論form_for。rails 4如何在form_for中傳遞object_id?

我root_path行動:

def home 
    @announcements = Announcement.page(params[:page]).order('id DESC') 
    end 

這裏是我的通告循環:

<% @announcements.each do |announcement| %> 
      . 
      . 
      . 
     <div class="create_comment form-inline"> 
       <%= form_for(announcement.comments.build) do |form| %> 
          <%= form.label :author, "Autor:" %> 
          <%= form.text_field :author, class: "form_control" %> 

          <%= form.label :content, "Treść:" %> 
          <%= form.text_field :content, class: "form_control" %> 

          <%= form.submit "Dodaj!", class: "btn btn-primary", url: comments_path %> 

       <% end %> 
     </div> 
    </div> 
<% end %> 

這裏是我的評論創建行動:

def create 
     @announcement = Announcement.find(params[:comment_id]) 
    @comment = @announcement.comments.new(comments_params) 
    if @comment.save 
     flash[:success] = "Komentarz dodano" 
     redirect_to root_path 
    else 
     render 'static_pages/home' 
    end 
    end 
private 

def comments_params 
     params.require(:comment).permit(:author,:content) 
    end 

但我得到一個錯誤:Couldn找不到公告ID

我知道我可以使用hidden_​​field並將其傳遞給comments_params,但這不是安全的解決方案。

我剛開始我的Rails冒險,所以如果有人知道我的錯誤在哪裏,請嘗試做出完整的解釋。

回答

0

好吧,來自@notulysses的幫助,我把它提供給瞭解決方案。被需要

Chenges進行:

首先在routes.rb中:需要註釋中嵌套在公告中,要加入適當的。

resources :announcements, only: [:new,:create,:update,:edit,:destroy,:show] do 
    resources :comments, only: [:create, :destroy] 
    end 

其次在comments_controller公告應由announcement_params被找到:

@announcement = Announcement.find(params[:announcement_id]) 

而且由第三方(這是我的一部分:)),我需要適當集中的form_for屬性。

form_for(announcement.comments.create, url: announcement_comments_path(announcement.id)) 

它需要url:param,因爲根在不同的控制器然後評論。

Yupi !!!!

相關問題