2014-03-27 35 views
0

我有一個表單,允許用戶在組中顯示方法發佈。發佈後,我想重定向到顯示新帖子的同一頁面。我正在使用以下內容,但出現下面的錯誤。我不確定爲什麼@group是零,因爲我已經在我的組控制器的顯示中定義了它。重定向到顯示在另一個控制器(Rails)

沒有路由匹配{:ID =>零}缺少必需的鍵:[:ID] 爲 redirect_to的group_path(@group)

<%=form_for([@post]) do |f| %> 
<%= render 'shared/error_messages', object: f.object %> 
    <div class = "field"> 
     <%= f.label :event_name %> 
     <%= f.collection_select(:event_id, @events, :id, :title) %> 
    </div> 
    <div class = "field"> 
     <%= f.text_area :comment, placeholder: "New Post..." %> 
    </div> 
     <%= f.hidden_field :user_id, value: current_user.id %> 
    <%=f.submit "Submit", class: "btn btn-large btn-primary" %> 
<%end%> 


class PostsController < ApplicationController 

    def create 
    if @post = Post.create(post_params) 
     flash[:success] = "Post Created!" 
     redirect_to group_path(@group) 
    else 
     redirect_to group_url 
     flash[:alert] = "Sorry - Post not created." 
    end 
    end 
end 


    def show 
    @event = @group.events.build 
    @post = Post.new 
    @events = @group.events.includes(:posts) 
    @group = Group.find(params[:id]) 
    end 

回答

2

在你創建你的行動嘗試使用@group實例變量。您尚未在創建操作中定義它,因此如果要使用它,您需要在其中創建它。由於創建調用是在一個單獨的請求週期中,因此您在show動作中定義的實例變量不可用。

更新: 要拿到小組第一,如果你有一個belongs_to的和事項標識事件:組你會怎麼做:

event = Event.find(event_id) 
@group = event.group 
+0

我如何找到@group ...我的表單只傳遞event_id,而不是group_id。在我的應用程序中有一組has_many事件。 – kyle

+0

如果事件有belongs_to:組,則可以從事件中獲取組。 – Coenwulf

2

create動作設定@group。您還沒有爲@group分配任何值,這就是您遇到錯誤的原因。

編輯

根據您的評論A Group has_many events所以你可以找到如下的組:

@group = Event.find(params[:event_id]).group 
+0

謝謝 - 我試圖做到這一點爲好,像這樣,但沒有骰子: @group = Group.find(params [:event_id]) – kyle

+0

@kyle查看我更新的答案。 –

相關問題