我正在学习Rails,并制作了一个reddit克隆,以帮助我理解路由是如何工作的。
每个帖子都有减法。我的路线文件中有以下内容:
resources :subreddits do
resources :posts
end 通过这种方式,我可以使用以下网址创建新的帖子:
/subreddits/:subreddit_id/posts/new(.:format)示例:
http://localhost:3000/subreddits/1/posts/new但是,我仍然需要在新的帖子表单中指定我想要发布的内容属于什么内容。我想要的是一个隐藏的字段,它将subreddit id设置为正确的字段。正确的一个是在URL中给出的。
这就是我目前的情况:
=simple_form_for @post, html: {multipart: true} do |f|
-if @post.errors.any?
#errors
%h2
=pluralize(@post.errors.count, "error")
prevented this pin from saving
%ul
-@post.errors.full_messages.each do |msg|
%li= msg
.form-group
=f.input :title, input_html: {class: 'form-control'}
.form-group
=f.input :content, input_html: {class: 'form-control'}
=f.hidden_field :subreddit_id, :value => @post.subreddit_id
=f.button :submit, class: "btn btn-primary"我得到以下错误:
No route matches {:action=>"show", :controller=>"posts", :id=>33, :subreddit_id=>nil} missing required keys: [:subreddit_id]我认为这是因为我试图访问尚未创建的帖子的subreddit id。我该怎么解决这个问题?我是不是走错方向了?
发布于 2017-03-30 16:51:35
在new的posts_controller操作中,您将设置@subreddit实例变量
def new
@subreddit = Subreddit.find(params[:subreddit_id])
@post = Post.new
end在表单中,您需要更改第一行
= simple_form_for [@subreddit, @post], html: {multipart: true} do |f|:subreddit_id现在将在url中。
发布于 2017-03-30 14:58:03
试试这个,检查它是否有效。
= f.input :title, :as => :hidden, :input_html => { :value => "some value" }https://stackoverflow.com/questions/43121184
复制相似问题