Ruby on rails 使用非Railsy路线预填充表单
我有很多Rails模型的实例,Ruby on rails 使用非Railsy路线预填充表单,ruby-on-rails,routes,url,Ruby On Rails,Routes,Url,我有很多Rails模型的实例,Post。查看单个帖子时,我想创建一个表单来创建名为Comment的post的子项。我想用一个隐藏标记预先填充此表单,该标记包含post\u id,它是Comment中的外键 Railsy的方法是创建一条奇特的ish路线,例如: /comments/new/post/:post_id 但是,这会阻塞routes文件,并没有留下多少灵活性。假设我想在其他地方创建一个链接,预先填充表单的不同属性……然后我必须为此添加另一个路由 所以我想我要在/posts/show/:
Post
。查看单个帖子时,我想创建一个表单来创建名为Comment
的post
的子项。我想用一个隐藏标记预先填充此表单,该标记包含post\u id
,它是Comment
中的外键
Railsy的方法是创建一条奇特的ish路线,例如:
/comments/new/post/:post_id
但是,这会阻塞routes文件,并没有留下多少灵活性。假设我想在其他地方创建一个链接,预先填充表单的不同属性……然后我必须为此添加另一个路由
所以我想我要在/posts/show/:id
上创建这样的URL:
/comments/new?comment[post_id]=<%= @post.id %>
/comments/new?注释[post\u id]=
这样,我可以根据需要添加任何其他属性。我知道与此相关的优点,现在缺点是什么?只需使用
new\u comment\u path:comment=>{:post\u id=>@post.id}
创建这样的URL即可。如果你愿意,可以把它包装成助手
但是,/comments/new/post/:post_id
URL样式应该没有缺点,因为您还可以添加更多参数:
new_post_comment_path @post, :comment => { :additional => "parameters", ... }
会导致
/posts/:post_id/comments/new?comment[additional]=parameters&...
在你的行动中:
def new
@post = Post.find params[:post_id]
@comment = @post.build params[:comment]
end
并呈现您的表单