使用隐藏字段提交

时间:2018-03-23 21:16:19

标签: ruby-on-rails ruby-on-rails-5

我的问题与我的previous problem有关。它是通过使用嵌套路由解决的。但是没有使用嵌套资源就有不同的想法。我试着把它作为练习。但是当我提交数据时,会显示ActiveRecord::RecordNotFound in SentencesController#create

Rails.application.routes.draw do
    root 'stories#index'
    get 'stories/show'
  get 'stories/new'
  post 'stories/:story_id', to: 'sentences#create'
  resources :stories
  resources :sentences, only: [:create] 
end

shared / _sentence_form.html.erb是故事/ show_form.html.erb的一部分

<%= form_for(@sentence) do |f| %>
  <%= hidden_field_tag :story_id, value: @story.id %>
  <%= f.text_area :content, placeholder: "Compose new sentence..." %>
  <%= f.submit "Save"%>
<% end %>

SentencesController

class SentencesController < ApplicationController
    before_action :sentence_params
    before_action :find_story

    def create
        @sentence = find_story.sentences.build(sentence_params)
    if @sentence.save
      flash[:success] = "You wrote the continuation!"
      redirect_to root_url
    else
        flash[:danger] = "I did not save your words!"
        redirect_to "#"
    end
  end

  private

    def sentence_params
      params.permit(:content, :story_id)
    end

    def find_story
        @story = Story.find(params[:story_id])
    end
end

和型号:

class Sentence < ApplicationRecord
  belongs_to :story
  validates :story_id, presence: true
  validates :content, presence: true, length: { maximum: 150 }
end

我在控制器和视图中尝试了很多组合。当我在text_area中放入一些信息并单击“提交”时,他们不会保存。

2 个答案:

答案 0 :(得分:1)

param是嵌套的:

def find_story
  @story = Story.find(params[:sentance][:story_id])
end

但是,无论如何,嵌套路线都是更好的REST设计。

路线POST /stories/:story_id/sentances清楚地说明了行动的作用。

resources :stories do
  resources :sentences, only: [:create] 
end
<%= form_for([@story, @sentence]) do |f| %>
  <%= f.text_area :content, placeholder: "Compose new sentence..." %>
  <%= f.submit "Save"%>
<% end %>

这会将params[:story_id]正确传递为网址的一部分。

答案 1 :(得分:0)

我不确定这是解决问题的方法,但我相信

def sentence_params
  params.permit(:content, :story_id)
end

在某处需要:sentence。您的表单为form_for @sentence,因此我猜您的参数为params[:sentence][:content]或类似。

我相信您的错误发生在@story = Story.find(params[:story_id])行,对吧?确保表单中存在@story变量,并且可以找到记录。

相关问题