【问题标题】:Rails 4 render simple-form NEW in INDEXRails 4 在 INDEX 中呈现简单形式的 NEW
【发布时间】:2015-05-02 19:37:53
【问题描述】:

在尝试在索引中渲染新的 simple_form 时。我已经关注 http://guides.rubyonrails.org/v2.3.11/layouts_and_rendering.html ,在 2.2.2 渲染操作的视图中,我在 Posts#index 中收到错误 NoMethodError ,未定义的方法 `model_name' 用于 NilClass:Class

class PostsController < ApplicationController
	before_action :find_post, only: [:show, :edit, :update, :destroy]
	before_action :authenticate_user!,except:[:index,:show]

	def index
		@posts = Post.all.order("created_at DESC")
		render 'new'
	end
	
	def new
		@post = current_user.posts.build
	end




index.html.haml

- if user_signed_in?
	= link_to "New Post", new_post_path

- @posts.each do |post|
	%h2.post= link_to post.post, post
	%h4.post= link_to post.location, post
	%h4.post= link_to post.tag_list, post
	%p.date
		Published at
		= time_ago_in_words(post.created_at)
		by
		= post.user.email



_form.html.haml

= simple_form_for @post do |f|
	= f.input :post
	= f.input :location
	= f.input :tag_list
	= f.input :active
	= f.submit


new.html.haml

%h1 Post 

= render 'form'

【问题讨论】:

  • 你能发布日志吗?
  • @ahmadhamza 对不起什么日志?新的 Rails ..
  • 日志表示你的终端输出。
  • => Post(id: integer, post: text, location: string, tag_list: string, active: boo lean, created_at: datetime, updated_at: datetime, user_id: integer)
  • NilClass:Class 意味着你得到一个空数组。你能从终端粘贴确切的日志吗?它确实提到了行号和文件名。

标签: ruby-on-rails forms ruby-on-rails-4 activerecord simple-form


【解决方案1】:

让我们把事情弄清楚。

您的控制器有几个actions,它们基本上对应于“我想做什么......在一个页面呈现/AJAX 请求中”。我相信您不清楚的是,在同一页面上显示索引和显示表单,对应于唯一的控制器操作!

现在你想做的是,正如 ahmad hamza 建议的那样,在你的 index 操作中实例化两个变量

  • @posts 您将在其中放置所有帖子的列表(索引)
  • @new_post 对应于用户可以直接从索引添加的新帖子

    def index
        @posts = Post.all.order("created_at DESC")
        @new_post = current_user.posts.build
    end
    

现在,也许您还有其他操作要显示一个表单来创建新帖子,而不仅仅是在索引中。

这就是为什么我们通常写partials 来做这些事情。但是,一个好主意是让这些部分可在任何地方重用,而不限制变量名。

换句话说,你想要

/views/posts/_form.html.haml

= simple_form_for post do |f| # Notice : not @post but post 
    = ...

现在从您的索引文件中,您想显示一些内容和@new_post 的表单

/views/posts/index.html.haml

- if user_signed_in?
= link_to "New Post", new_post_path

- @posts.each do |post|
    %h2.post= link_to post.post, post
    %h4.post= link_to post.location, post
    %h4.post= link_to post.tag_list, post
    %p.date
        Published at
        = time_ago_in_words(post.created_at)
        by
        = post.user.email
- render 'form', post = @new_post

【讨论】:

  • 谢谢你的澄清,你的解释很有帮助,干杯
【解决方案2】:

尝试从控制器中删除render new,正如您已经在视图文件index.html.haml 文件中提到的那样。 此外,当您收到 NilClass 错误时,您的控制器将如下所示。:

def index
    @posts = Post.all.order("created_at DESC")
    @post = Post.new
end

【讨论】:

  • 谢谢你解决它。干杯
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-04-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多