중첩 된 경로가있는 has_one 모델을 매핑하는 방법과 RESTful 데이터베이스에 따라 /localhost:3000/users/1/profile/new,html.erb에 form_for를 추가하는 방법은 무엇입니까?중첩 된 경로와 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
답장을 보내 주셔서 감사합니다. 원래 프로필 속성은 사용자 여야한다고 생각했지만 하나의 양식에 중첩 된 모델에 대한 많은 기사와 달리 한 가지 모델과 관련된 많은 정보가 없습니다. 그래서 나는 이메일 * pwd 형식 -> 사용자 정보 -> 사용자 목표와 같은 작은 구성 요소로 나누기로 결정했습니다. profile_controller에서 작동해야하는 오류 메시지가 표시됩니다. 왜 작동하지 않는지 약간의 스트레스가 있습니다. 해시에 대한 두 가지 오류 메시지를 참조하십시오. – smileyUser
간단한 버그! 내가 오류를 일으키는 이주 rb 대신 schema.rb를 편집했습니다! – smileyUser
schema.rb를 편집하지 마십시오. 마이그레이션 할 때마다 다시 작성됩니다. 스키마를 편집하려면'rails g migration name_of_the_migration'을 실행하고 거기에 변경 사항을 작성하십시오. – Robin