eNd*_*ddy 8 polymorphism renderpartial ruby-on-rails
为什么我收到以下错误?
nil不是与ActiveModel兼容的对象.它必须实现:to_partial_path.
我认为错误可能与我正在使用的教程有关,当我使用Rails 4时.
这是型号代码:
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
Run Code Online (Sandbox Code Playgroud)
这是在_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) %>
Run Code Online (Sandbox Code Playgroud)
Rails 4中的Thoughtbot中级教程几乎没有什么复杂性,但是,将一个问题出现在将ActiveModel功能添加到普通的Ruby对象中.我在第3周的视频大约半小时标记处看到了这一点,而导师(AKA Mr Halogenandtoast)正在提取时间轴对象.
而不是:扩展ActiveModel :: Naming你想要包含ActiveModel :: Model - Rails 4更改,以便更容易使用普通对象.
class Timeline
include ActiveModel::Model
...
...
Run Code Online (Sandbox Code Playgroud)
对于Thoughtbot学习订阅者,有一个链接到讨论.强大的参数是这个优秀教程的另一个问题.
小智 4
您遇到的问题是因为数据库中的现有记录没有与其关联的内容。发生这种情况是因为您从非多态设置转变为多态设置。您需要做的是查找缺少 content_type 和 content_id 的喊叫并将其从数据库中删除。一旦删除这些,添加可能会很有用
validates_关联:内容
到您的 Shout 模型,以确保未来的数据不会最终“损坏”您的数据库。