2
我創建一個示例項目,但是當我試圖創建一個新的職位得到一個錯誤「未定義的方法創建無類」未定義的方法創建無類
我的代碼如下。
user.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_one :post, dependent: :destroy
end
post.rb
class Post < ActiveRecord::Base
belongs_to :user
end
posts_controller.rb
class PostsController < ApplicationController
def create
@user = current_user
if @user.post.blank?
@post = @user.post.create(params[:post].permit(:title, :text))
end
redirect_to user_root_path
end
end
new.html.erb
<%= form_for([current_user, current_user.build_post]) do |f| %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
但嘗試了很多次後,我做了一些改變,它開始工作,但我不知道兩個代碼之間有什麼區別。
user.rb
class User < ActiveRecord::Base
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :posts, dependent: :destroy
end
post.rb
class Post < ActiveRecord::Base
belongs_to :user
end
posts_controller.rb
class PostsController < ApplicationController
def create
@user = current_user
if @user.posts.blank?
@post = @user.posts.create(params[:post].permit(:title, :text))
end
redirect_to user_root_path
end
end
new.html.erb
<%= form_for([current_user, current_user.posts.build]) do |f| %>
<p>
<%= f.label :title %><br>
<%= f.text_field :title %>
</p>
<p>
<%= f.label :text %><br>
<%= f.text_area :text %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
我的routes.rb是
UserBlog::Application.routes.draw do
devise_for :users, controllers: { registrations: "registrations" }
resources :users do
resources :posts
end
# You can have the root of your site routed with "root"
root 'home#index'
end
請幫幫我,告訴我是什麼這兩個代碼之間的區別?
感謝您使用has_many關聯語法。 – jamesdlivesinatree