0
は、私は、次の2つのテーブルはへのアクセスにhas_manyモデルレコード
class CreateUsers < ActiveRecord::Migration
def self.up
create_table :users do |t|
t.string :name
t.string :phone
t.string :email
t.string :address
t.string :resume
t.timestamps
end
end
end
Class CreateResumeSections < ActiveRecordMigration
def self.up
create_table :resume_sections do |t|
t.string :section_name
t.string :html
t.timestamps
end
end
end
私は2つのモデル私users_controllerで
class User
has_many :resume_sections, :dependent => :destroy
attr_accessor :section_layout
after_save :save_sections
private
def save_sections
self.section_layout = ###Someother logic here that sets this variable
end
end
class ResumeSection
belongs_to :user
end
を以下している移行で定義されている、私は次のコード
class UserController < ApplicationController
def create
@user = User.new(params[:user])
@user.save
@user.section_layout.each {|key,value|
rs = ResumeSection.new(:section_name => key, :html => value, :user => @user)
rs.save
}
end
end
に持っています
私の見解では、私は次のコードを持っています
<% @user.resume_sections.each do |section| %>
<%= section.section_name %>
<%= section.html %>
<% end %>
ビューでNil:NilClassの未定義メソッドエラーが発生します。 @ user.resume_sectionsという式は、作成してUsersControllerに保存したレコードを返しません。代わりにそれは私にnilを返します。私がデータベースをチェックすると、レコードがそこにあります。
これらのレコードにアクセスするための式@ user.resume_sectionsは正しい式ですか?
おかげ ポール
これは正しいです... @ ppaul74、あなたのモデルに 'has_many'を使用するだけで、魔法のようにDBに関連付けが作成されるわけではありません。 'has_many'、' belongs_to'などはすべて、DBに定義されている適切な外部キーに依存しています。 –
スポットがあります。 '' belongs_to' "を持つモデルは外部キーを含んでいなければなりません。 – Substantial