0

这是我现在的代码...

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。我知道我需要向我的控制器添加一个构建方法,但我不确定是否应该将它添加到文章或注册控制器。任何帮助表示赞赏!

4

1 回答 1

0

在你的routes.rb你可以制作嵌套资源:

resources :articles do
  resources :registrations
end

然后你可以在你的助手中使用polymorphic_url方法的“魔法”来创建你的链接:link_to

<%= link_to 'Register', [:new, @article, :registration] %>
于 2012-11-27T20:48:16.040 回答