问题描述
|
我有3个对象:用户,旅行,积分。
一个用户有很多旅行,一个旅行有很多积分,一个用户属于一个旅行。
旅行还具有一个布尔属性(:open),该属性指示它是否处于诅咒状态。
问题是我无法在积分表中保存当前旅行的“ travel_id \”。
这是代码:
class Point < ActiveRecord::Base
belongs_to :travel,:foreign_key=> \"travel_id\"
belongs_to :user,:foreign_key=> \"user_id\"
end
class Travel < ActiveRecord::Base
has_one :user,:foreign_key => \"user_id\"
has_many :ways
has_many :points
attr_accessible :description,:start_date,:last_date
validates_date :last_date,:on_or_after => :start_date
end
积分控制器:
...
def create
@point = Point.new(params[:point])
@point.user_id = current_user.id
@travel = current_user.travels.find(:all,:conditions => {:open => true})
@point.travel_id = @travel.id
respond_to do |format|
if @point.save
format.html { redirect_to(@point,:notice => \'Point was successfully created.\') }
format.xml { render :xml => @point,:status => :created,:location => @point }
else
format.html { render :action => \"new\" }
format.xml { render :xml => @point.errors,:status => :unprocessable_entity }
end
end
end
...
每当我尝试保存新点时,@ point.travel_id = -614747648
解决方法
在这里进行固定可能会导致一些问题。
首先,当键与关系名称+
_id
相同时,无需指定:foreign_key
。
其次,您不需要(通常不应该)直接设置foo_id
字段; @point.user = current_user
比较常见。
第三,造成问题的直接原因是,将@travel
设置为find(:all,...)
调用的结果-因此它是Travel
个对象的数组。您要保存到ѭ9中的内容将是Ruby的@travel
数组的内部ID,而不是单行的数据库ID。