如何映射has_one模型與嵌套路由以及如何添加form_for for /localhost:3000/users/1/profile/new,html.erb下面的RESTful數據庫?嵌套路線和form_for和使用has_one和belongs_to模型
用戶有一個配置文件。
模型
class Profile < ActiveRecord::Base
attr_accessible :name, :surname
belongs_to :user
end
class User < ActiveRecord::Base
attr_accessible :email, :email_confirmation, :password, :password_confirmation
has_secure_password
has_one :profile, dependent: :destroy
end
resources :users do
resources :profiles (note: has_one profile)
resources :progress_charts
resources :calories_journals
end
的意見/型材/ new.html.erb
<h1>About You</h1>
<div class="row">
<div class="span6 offset3">
<%= form_for(@profile) do |f| %>
<%= render 'shared/error_messages' %>
<%= f.label :name %>
<%= f.text_field :name %>
<%= f.label :surname %>
<%= f.text_field :surname %>
<%= f.submit "Create my account", class: "btn btn-large btn-primary" %>
<% end %>
</div>
</div>
控制器:Profiles_controller.rb 兩個錯誤,我發現,我不明白爲什麼它不加工。
class ProfilesController < ApplicationController
def index
end
def show
end
def new
# @user = User.find(params[:id]) # Error message: Couldn't find User without an ID
# @profile = @user.build_profile()
@profile = current_user.build_profile(params[:id]) # Error message: unknown attributes: user_id
end
def edit
end
def create
end
def update
end
def destroy
end
end
助手:SessionHelper(以說明CURRENT_USER) 模塊SessionsHelper DEF sign_in(用戶) cookies.permanent [:remember_token] = user.remember_token self.current_user =用戶 端
def signed_in?
!current_user.nil?
end
def current_user=(user)
@current_user = user
end
def current_user?(user)
user == current_user
end
def current_user
@current_user ||= User.find_by_remember_token(cookies[:remember_token])
end
def sign_out
self.current_user = nil
cookies.delete(:remember_token)
end
def signed_in_user
unless signed_in?
store_location
redirect_to signin_path, notice: "Please sign in."
end
end
end
感謝您的回覆,原來我以爲的資料特徵應該是用戶,但我發現就不像關於嵌套模型的單一形式很多文章一個模型多種形式的信息。所以我決定把它分解成更小的組件,比如email * pwd form - >關於用戶 - >用戶目標。在profile_controller中,我收到了應該工作的錯誤消息,但我強調爲什麼它不起作用。用哈希查看兩條錯誤消息。 – smileyUser
簡單的錯誤!我編輯schema.rb而不是遷移rb導致錯誤! – smileyUser
永遠不要編輯schema.rb,它重新遷移每次。如果您需要編輯您的架構,運行'軌摹遷移name_of_the_migration',還有寫你的變化。 – Robin