我有一个简单的 has_many belongs_to 关系,我想为 belongs_to 模型的视图包含父对象,我已经取得了一些成功,但我希望它能够更好地工作。
class Submission < ActiveRecord::Base
belongs_to :user
belongs_to :contest
end
class Contest < ActiveRecord::Base
belongs_to :user
has_many :submissions, :dependent => :destroy
end
在可行的情况下,我通过将竞赛 ID 放在 url 中将其传递给提交:
<%= link_to 'Submit Contest Entry', new_submission_path(:contest_id => @contest.id),
:class => 'btn btn-primary btn-large mleft10' %>
因此,结合 hidden_field:
<%= f.hidden_field :contest_id %>
以及控制器中的 find_contest 方法(使用 before_filter 调用):
def find_contest
#the next line is giving the error (line 76)
@contest = Contest.find(params[:submission][:contest_id])
end
使其适用于提交/新建,但是如何将查找添加到仅适用于不止一个页面的控制器中,就像我想在显示和索引中访问一样。现在,我收到一个错误:
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'
[编辑]为提交添加显示操作:
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