私は別のものに外部キーを持つオブジェクトに対してRailsで更新フォームを作成しようとしています。ただし、このエラーがスローされます。私はまだRuby on Railsで非常にグリーンホーンであり、ビデオチュートリアルに従っているので、これをどのように解釈するのかは分かりません。 NilClassRailsが "undefined method` [] 'for nil:NilClass "をスローしました。
:私はライン@prf = update_prof_params["profiles_attributes"]["0"]
の下に、現在使用して、レール5.0.0 travelers_controllers.rb
で
午前はエラーに
未定義のメソッド `[]」nilのためにスロー
edit.html.erb
<div class="col-md-7 col-md-offset-3 main"> <% provide(:title, "Edit user")%> <center><h1>Update your profile</h1></center> <%= form_for(@person) do |f| %> <%= render 'shared/error_messages' %> <div class="col-md-12"> <%= render 'layouts/profilefields', f: f %> <%= f.submit "Save Changes", class: "btn btn-large btn-primary" %> </div> <% end %> </div>
_profilefields.html.erb
<%= f.fields_for :profiles do |prf|%> <!-- <% if [email protected]["avatar"].blank? %> <%= image_tag @contactInfo.avatar_url(:medium).to_s, :class=>"profilePhoto" %> <% end %> <div class="photoPreview"> <i class="fa fa-upload photoUpload"></i> <p id="uploadClick">Click to Upload</p> </div> <%= prf.file_field :avatar, accept: 'image/png,image/gif,image/jpeg, image/jpg', id: 'uploadAvatar' %> <p class="deletePhoto">Delete</p> --> <%= prf.label :about %> <%= prf.text_field :about, :class => "form-control" %> <%= prf.label :why %> <%= prf.text_field :why, :class => "form-control" %> <%= prf.label :goals %> <%= prf.text_field :goals, :class => "form-control" %> <%= prf.hidden_field :traveler_id, value: current_traveler.id %> <% end %>
travelers_controller.rb
class TravelersController < ApplicationController def edit @person = Traveler.find(params[:id]) @profileInfo = Profile.find_or_initialize_by(traveler_id: params[:id]) #@profileInfo[:email] = current_traveler.email #This builds the form @person.build_profile(@profileInfo.attributes) end def show end def update @prf = update_prof_params["profiles_attributes"]["0"] @prof = Profile.find_or_create_by(traveler_id: current_traveler.id) if @prof.update_attributes(prf) flash[:success] = "Profile updated" redirect_to feed_path else # Failed. Re-render the page as unsucessful render :edit end end private def update_prof_params params.require(:traveler).permit(profiles_attributes: [:about, :why, :goals, :traveler_id]) end end
とモデル
TravelersControllerでclass Profile < ApplicationRecord belongs_to :traveler, foreign_key: "traveler_id" end class Traveler < ApplicationRecord # Include default devise modules. Others available are: # , :lockable, :timeoutable and :omniauthable devise :database_authenticatable, :registerable, :confirmable, :recoverable, :rememberable, :trackable, :validatable has_one :profile end
これは奇妙です、この 'update_prof_params [" profiles_attributes "] [" 0 "]'を実行する目的は何ですか? –
正直なところ、私は本当に確信していません。それはチュートリアルだった。私はそれを完全にommittingしようとしていて、@ prof.update_attributes(update_prof_params)とそれを変更すると、フォームは大丈夫ですが、問題は新しい値が保存されずにデータベースに更新されるようになります。 –