Rymo4
Rymo4

Reputation: 471

Create method problem in Ruby on Rails

I have a rails app that involves users, essays, and rankings. It's pretty straightforward but I'm very new to rails. The part I'm having trouble with right now is the create method for the rankings.

The Essay class has_many :rankings and the Ranking class belongs_to :essay

in the rankings controller I have:

def create
   @ranking = @essay.rankings.build(params[:ranking])
   flash[:success] = "Ranking created!"
   redirect_to root_path
end

but I get the error: undefined method `rankings' for nil:NilClass

I need each ranking to have an essay_id, and I believe build updates this for me.

I thought that rails give me the rankings method because of the relation I set, and why is @essay nil?

Thanks in advance

Upvotes: 0

Views: 311

Answers (2)

David
David

Reputation: 7303

I think this is what you intend to do:

# EssayController#new
def new
  @essay = Essay.new(params[:essay])
  @ranking = @essay.rankings.build(params[:ranking])
  #...
 end

Take a look at nested model forms , it should get you in the right direction.

Upvotes: 0

coreyward
coreyward

Reputation: 80041

Build doesn't save. You should be using new and then save. I'd provide you sample code, but you haven't really given us a clear picture of what you have going on. That @essay instance variable is being used before it's defined, and I'm not really sure how your application is determining which essay the ranking belongs to.

You might wanna give Rails Guides a read.

Upvotes: 1

Related Questions