这是我现在的代码......
class Article < ActiveRecord::Base
has_many :registrations
class Registration < ActiveRecord::Base
belongs_to :article
#app/views/articles/show.html.erb
<%= link_to 'Register', new_registration_path({:article_id => @article}) %>
#app/views/registrations/_form.html.erb
<%= f.hidden_field :article_id %>
#app/controllers/registrations_controller.rb
def new
@registration = Registration.new
@registration.article = Article.find params[:article_id]
..这只是很好的。但是,我想摆脱app / views / articles / show.html.erb中的代码并使用路由执行此操作...
<%= link_to 'Register', new_article_registration_path(@article) %>
...我还想摆脱我在注册视图中使用的hte hidden_field。我知道我需要为我的控制器添加一个构建方法,但我不确定是否应该将它添加到文章或注册控制器中。任何帮助表示赞赏!
答案 0 :(得分:0)
在routes.rb
中,您可以制作嵌套资源:
resources :articles do
resources :registrations
end
然后,您可以使用link_to
帮助程序中polymorphic_url方法的“魔力”来建立链接:
<%= link_to 'Register', [:new, @article, :registration] %>