开发者

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 an开发者_开发知识库d 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


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜