表单创建对象,但没有传入params

时间:2015-03-23 19:17:30

标签: ruby-on-rails forms

我正在尝试创建一个简单的表单提交来为博客类型的网站创建帖子。我似乎无法获得提交参数的表格。如果我删除模型中的验证,我可以创建具有唯一ID的对象,但就params而言它们是完全空白的。

posts_controller.rb

 class PostsController < ApplicationController

def index
    @posts = Post.all
end

def show
    @post = Post.find(params[:id])
end

def new
    @post = Post.new
end

def create
    @post = Post.new(post_params)
    if @post.save
        redirect_to post_path(@post), :notice => "Post was created successfully."
    else
        render :new
    end
end

private
def post_params
    params.require(:post).permit(:id)
end

new.html.erb

  <%= form_for(@post) do |f| %>
  <% if @post.errors.any? %>
  <div id="error_explanation">
   <ul>
     <% @post.errors.full_messages.each do |msg| %>
     <div><%= msg %></div>
     <% end %>
    </ul>
</div>
<% end %>
 <% end %>

<%= form_for(@post) do |f| %>
  <ol class="formdivst">
  <%= f.label :title %><br />
  <%= f.text_field :title %>
  <%= f.label :content_md %><br />
  <%= f.text_field :content_md %>
<div>
  <%= f.file_field :image %>
  <div class="actions">
    <%= f.submit "Submit" %>
  </div>
</ol>
<% end %>

posts.rb(模特)

class Post < ActiveRecord::Base
  # Use friendly_id
  extend FriendlyId
  friendly_id :title, use: :slugged

  # Markdown
  #before_save { MarkdownWriter.update_html(self) }

  # Validations
  validates :title, presence: true, length: { maximum: 100 }, uniqueness: true
  validates :content_md, presence: true

  # Pagination
  paginates_per 30

  # Relations
  belongs_to :user

  # Scopes
  scope :published, lambda {
    where(draft: false)
    .order("updated_at DESC")
  }

  scope :drafted, lambda {
    where(draft: true)
    .order("updated_at DESC")
  }

  has_attached_file :image, styles: { small: "64x64", med: "100x100", large: "200x200" }

end

的routes.rb

app::Application.routes.draw do
  root "pages#home"
  resources :posts
  get "home", to: "pages#home", as: "home"
  get "inside", to: "pages#inside", as: "inside"
  get "/contact", to: "pages#contact", as: "contact"
  post "/emailconfirmation", to: "pages#email", as: "email_confirmation"

  devise_for :users

  namespace :admin do
    resources :posts
    root "base#index"
    resources :users
    get "posts/drafts", to: "posts#drafts", as: "posts_drafts"
    get "posts/dashboard", to: "posts#dashboard", as: "posts_dashboard"
  end

end

1 个答案:

答案 0 :(得分:1)

这里的问题是你没有像你应该做的那样定义post_params(如果使用Rails 4或使用StrongParameters gem):

# posts_controller
def post_params
  params.require(:post).permit([:list_of_allowed_attributes_here])
end

我看到你正在使用FriendlyId。为了找回带有友好ID的记录,你必须找到它:

@post = Post.friendly.find(params[:id])

因为params[:id]不是Rails所期望的常规整数,而是FriendlyId(包含关键字和内容的字符串)。