vjnan369
vjnan369

Reputation: 853

unable to access model attributes in view

I created a model named Group. which have name,sesssionId attributes. in my index.html.erb i added

<%=form_for(@group) do |f|%>
<%=f.text_field :name %>
<%=f.submit%>
<%end%>

in groups controller i stored attributes in Group model

def index
@group = Group.new
@groups = Group.all
end

def create
 #here i am getting "session" with some other code...
 params[:group][:sessionId] = session.session_id
 @group = Group.create(strong_param)
 #@group = Group.new(params[:group])
 if @group.save
   redirect_to("/room/"[email protected]_s)
 else
   render :controller => 'groups', :action => 'index'
 end
end

def room
end
private 
def strong_param
    params.require(:group).permit(:name,:sessionId)
end

in room.html.erb

<p>unique url for this room is <%[email protected]%></p>

when I tried to access group_id in room view it shows

undefined method `id' for nil:NilClass

I am unable to access those model attributes in above view. And i can able to access them in index view. thanks in advance.

Upvotes: 0

Views: 352

Answers (3)

Marek Lipka
Marek Lipka

Reputation: 51161

You should set @group in room action:

def room
  @group = Group.find(params[:group_id])
end

I would also advice you to learn about routing in Rails, so you can clean your controller a little bit.

Upvotes: 1

Yury Lebedev
Yury Lebedev

Reputation: 4015

In the controller action for the "/room/:id", to which you redirect the user after creating a group, the @group variable is not set, therefor you get the error.

Upvotes: 1

Pavan
Pavan

Reputation: 33542

undefined method `id' for nil:NilClass

The error is because you don't have @group in room method.

Try the below code

def room
  @group = Group.find(params[:id])
end

Upvotes: 4

Related Questions