Ruby on rails 在“属于”关系中保存ID时出现问题
我有3个对象:用户、旅行、积分 一个用户有很多次旅行,一次旅行有很多点,一个点属于一个旅行e一个用户 旅行还有一个布尔属性(:open),它告诉你它是否处于诅咒状态 问题是我无法在积分表中保存当前行程的“行程id” 代码如下:Ruby on rails 在“属于”关系中保存ID时出现问题,ruby-on-rails,has-many,belongs-to,Ruby On Rails,Has Many,Belongs To,我有3个对象:用户、旅行、积分 一个用户有很多次旅行,一次旅行有很多点,一个点属于一个旅行e一个用户 旅行还有一个布尔属性(:open),它告诉你它是否处于诅咒状态 问题是我无法在积分表中保存当前行程的“行程id” 代码如下: class Point < ActiveRecord::Base belongs_to :travel, :foreign_key=> "travel_id" belongs_to :user, :foreign_key=> "user_
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
每次我试图保存一个新的点,@point.travel\u id=-614747648在这里修复可以做一些事情 首先,当键与关系名+
\u id
相同时,不需要指定:foreign\u key
其次,您不需要(通常也不应该)直接设置foo\u id
字段;通常的做法是@point.user=current\u user
第三,也是问题的直接原因,是
@travel
已设置为查找(:all…)
调用的结果-因此它是travel
对象的数组。您保存到@point.travel\u id
中的内容将是@travel
数组的Ruby内部id,而不是一行的数据库id。我已经更改了@point.travel\u id=@travel[0],它工作得非常好。真的非常感谢你所做的一切。
...
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
...