[英]relationship belongs_to to belongs_to in ruby on rails
我在Rails的两个模型之间有一个归属关系到归属关系。 我有模型用户和模型启动
用户模型是一个设计模型(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:对不起,我的英语还不是很好。
我是Rails的新手,所以如果我错了,请有人纠正我,但我认为您不能拥有2个彼此“属于”的模型。 1必须属于,1必须具有has_many或has_one(编辑:根据注释,应该为:has_one
。
我认为这可能是您要寻找的:
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
has_one :startup # not has_many :startups
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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.