kyle
kyle

Reputation: 87

Redirect to show in another controller (Rails)

I have a form that allows the user to Post in the a group Show method. Upon posting, I want to redirect to the same page showing the new post. I'm using the following, but I get the error below. I'm not sure why @group is nil, because I've defined it in the show of my group controller.

No route matches {:id=>nil} missing required keys: [:id] for 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

Upvotes: 0

Views: 889

Answers (2)

Coenwulf
Coenwulf

Reputation: 1937

In your create action you attempt to use the @group instance variable. You haven't defined it in the create action so you'll need to create it there if you want to use it. Since the call to create is in a separate request cycle the instance variables you defined in the show action are not available.

Update: To get the group if you have an event_id and event belongs_to :group you would do:

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

Upvotes: 2

Kirti Thorat
Kirti Thorat

Reputation: 53018

Set @group in create action. You have not assigned any value to @group there which is why you are getting error.

EDIT

As per your comment A Group has_many events so you can find the group as below:

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

Upvotes: 2

Related Questions