加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 为什么我得到’nil’不是与ActiveModel兼容的

发布时间:2020-12-17 04:26:28 所属栏目:百科 来源:网络整理
导读:为什么我收到以下错误? nil is not an ActiveModel-compatible object. It must implement :to_partial_path. 我认为错误可能与我正在使用的教程有关,当我使用Rails 4时使用Rails 3.2. 这是型号代码: class DashboardsController ApplicationController de
为什么我收到以下错误?

nil is not an ActiveModel-compatible object. It must implement :to_partial_path.

我认为错误可能与我正在使用的教程有关,当我使用Rails 4时使用Rails 3.2.

这是型号代码:

class DashboardsController < ApplicationController
  def show
    @text_shout = TextShout.new
    @photo_shout = PhotoShout.new
    @shouts = current_user.shouts
  end
end

class PhotoShoutsController < ApplicationController
  def create
    content = build_content
    shout = current_user.shouts.build(content: content)
    if shout.save
      redirect_to dashboard_path
    else
      flash.alert = "Could not shout."
      redirect_to dashboard_path
    end
  end

  private
  def build_content
    PhotoShout.new(photo_shout_parameters)
  end

  def photo_shout_parameters
    params.require(:photo_shout).permit(:image)
  end
end

这是在_shout.html partial上发生错误的视图代码

# app/view/dashboards/show.html.erb
<%= form_for @text_shout do |form| %>
   <%= form.text_field :body,placeholder: 'Shout content here' %>
   <%= form.submit 'Shout' %>
<% end %>

<%= form_for @photo_shout do |form| %>
   <%= form.file_field :image %>
   <%= form.submit 'Shout' %>
<% end %>

<%= render @shouts %>

# app/view/shouts/_shout.html.erb
<%= div_for shout do %>
  <%= link_to shout.user.username,shout.user %>
  shouted
                                 +---------------------------------+
  <%= render shout.content %> <--| ERROR "nil' is not an Active "  |
                                 | "Model-compatible object"       |
                                 +---------------------------------+
  <%= link_to time_ago_in_words(shout.created_at),shout %>
<% end %>

# app/views/photo_shouts/_photo_shout.html.erb
<%= image_tag photo_shout.image.url(:shout) %>

解决方法

您遇到的问题是因为您的数据库中存在没有与之关联的内容的现有记录.发生这种情况是因为您从非多态设置变为多态设置.您需要做的是查找缺少content_type和content_id的呼叫,并将其从数据库中删除.删除后,添加可能很有用

validates_associated:内容

到您的Shout模型,以确保将来的数据不会“破坏”您的数据库.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读