我正在尝试为推文添加标题以在Rails中进行练习。我一直在编写推文的页面上收到此错误:
undefined method `title'
它突出显示app/views/shared/_micropost_form.html.erb
文件的第4行:
<%= form_for(@micropost) do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="field">
<%= f.text_area :title, placholder: "Event name" %>
<%= f.text_area :content, placeholder: "Compose new micropost..." %>
</div>
<%= f.submit "Post", class: "btn btn-large btn-primary" %>
<% end %>
这是我的microposts_controller.rb
文件:
class MicropostsController < ApplicationController
before_action :signed_in_user, only: [:create, :destroy]
before_action :correct_user, only: :destroy
def create
@micropost = current_user.microposts.build(micropost_params)
if @micropost.save
flash[:success] = "Micropost created!"
redirect_to root_url
else
@feed_items = []
render 'static_pages/home'
end
end
def destroy
@micropost.destroy
redirect_to root_url
end
private
def micropost_params
params.require(:micropost).permit(:content)
end
def correct_user
@micropost = current_user.microposts.find_by(id: params[:id])
redirect_to root_url if @micropost.nil?
end
end
和我的[ts]_create_microposts.rb
文件:
class CreateMicroposts < ActiveRecord::Migration
def change
create_table :microposts do |t|
t.string :content
t.integer :user_id
t.string :title
t.timestamps
end
add_index :microposts, [:user_id, :created_at]
end
end
答案 0 :(得分:1)
好像你可能忘记了迁移:
rails generate migration AddTitleToMicroposts title:string
或可能是db:migrate
。
此外,您在第4行拼错了占位符。
答案 1 :(得分:0)
您在app/views/shared/_micropost_form.html.erb
文件中错误拼写占位符
见行:<%= f.text_area :title, placholder: "Event name" %>
一旦将其更正为占位符,一切都将正常工作