Passing params in rails... Breakthrough in understanding params, aka, the "aha" moment

Posted by Brian McDonough on Stack Overflow See other posts from Stack Overflow or by Brian McDonough
Published on 2012-12-02T00:02:50Z Indexed on 2012/12/02 23:04 UTC
Read the original article Hit count: 242

Filed under:
|

I have a simple has_many belongs_to relationship and I want to include the parent object for the view of the belongs_to model and I have had some success, but I want it to work better.

class Submission < ActiveRecord::Base
  belongs_to :user
  belongs_to :contest
end
class Contest < ActiveRecord::Base
  belongs_to :user
  has_many :submissions, :dependent => :destroy
end

In the case that works, I pass contest_id to submissions by placing it in the url:

   <%= link_to 'Submit Contest Entry', new_submission_path(:contest_id => @contest.id), 
                            :class => 'btn btn-primary btn-large mleft10' %>

So that, combined with a hidden_field:

 <%= f.hidden_field :contest_id %>

And a find_contest method in the controller (called with a before_filter):

def find_contest
  #the next line is giving the error (line 76)
  @contest = Contest.find(params[:submission][:contest_id])
end

Makes it work for submissions/new, but how do I add a find to the controller that just works across more than that one page, like if I want to access in show and index. Right now, I get an error:

Started GET "/submissions?contest_id=5" for 127.0.0.1 at 2012-12-01 16:01:45 -0800
Processing by SubmissionsController#index as HTML
  Parameters: {"contest_id"=>"5"}
  User Load (0.3ms)  SELECT "users".* FROM "users" WHERE "users"."id" = 2 ORDER BY users.created_at DESC LIMIT 1
Completed 500 Internal Server Error in 37ms

NoMethodError (undefined method `[]' for nil:NilClass):
  app/controllers/submissions_controller.rb:76:in `find_contest'

[edited] Adding show action for submissions:

before_filter :find_contest, :except => [:index, :show, :edit, :update, :destroy]

def find_contest
  @contest = Contest.find(params[:submission][:contest_id])
end

def show
  contest_id = @submission.contest_id
  @submission = @commentable = Submission.find(params[:id])
  @comments = @commentable.comments.order(:created_at).reverse
  respond_to do |format|
    format.html  # show.html.erb
    format.json  { render :json => @submission }
  end
end

© Stack Overflow or respective owner

Related posts about ruby-on-rails-3

Related posts about params