私は、レール内の2つのモデルの間にbelongs_toとbelongs_toの関係を持っています。モデルユーザーとモデルスタートアップがあります
モデル User はデバイスモデル (gem devise) です。
これは私のコードです。
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :token_authenticatable
# :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :confirmable
# Setup accessible (or protected) attributes for your model
attr_accessible :email, :password, :password_confirmation, :remember_me, :startup_name
# attr_accessible :title, :body
belongs_to :startup
end
そして、これは私のモデルのスタートアップです
class Startup < ActiveRecord::Base
attr_accessible :angelist, :capitalraise, :category, :country, :currentlocation, :description, :facebook, :linkedin, :name, :round, :startupchile, :twitter, :user_id
has_one :entrepreneus, dependent: :destroy
belongs_to :user
end
また、私のスキーマでは、スタートアップ テーブルに「user_id」を追加しました。
これは追加された add_index です
add_index "startups", ["user_id"], :name => "index_startups_on_user_id"
(もちろん移行しました)
最初にスタートアップを作成するときは、user_id なしでオブジェクトを作成しますが、update_attributes を使用してオブジェクトに user_id を追加します。(startup_controller 内)。これがコードです
def create
@startup = Startup.new(params[:startup])
@startup.update_attributes(:user_id => current_user.id )
respond_to do |format|
if @startup.save
format.html { redirect_to @startup, notice: 'Startup was successfully created.' }
format.json { render json: @startup, status: :created, location: @startup }
else
format.html { render action: "new" }
format.json { render json: @startup.errors, status: :unprocessable_entity }
end
end
end
コンソールで次のことを行います(rails c --sandbox)
u = User.first (retrieve the user perfectly, the id is equal to 1)
u.startup (retrieve null)
しかし、これを行う場合:
s = Startup.find_by_user_id(1) // retrieve the data
u.startup でスタートアップに関連付けられたデータを取得できないのはなぜですか?
何か案が ?。ありがとう
PDT: 申し訳ありませんが、私の英語はまだあまり上手ではありません。