我的Rails应用程序有一个问题,我将它部署到Heroku。当我对我的俱乐部资源进行POST时,它说:
Parameters: {"utf8"=>"✓","authenticity_token"=>"MqScpac6l9MMHdPBehqfq0mTwLCCZq2dlZLVY6wt+ow=",
"club"=> {"name"=>"Grün Weiß Club im PSV Kiel"}, "commit"=>"absenden"}
2012-12-31T03:10:49+00:00 app[web.1]: NoMethodError (undefined method `user_id=' for # <Club:0x000000061269b0>):
2012-12-31T03:10:49+00:00 app[web.1]:
2012-12-31T03:10:49+00:00 app[web.1]:
2012-12-31T03:10:49+00:00 app[web.1]: app/controllers/clubs_controller.rb:47:in `create'
我的模型是这样的:
class Club < ActiveRecord::Base
default_scope :order => 'name ASC'
attr_accessible :name, :user_id
belongs_to :user
has_many :memberships
has_many :users, :through => :memberships, :order => 'name ASC'
validates :name, presence: true, :uniqueness => true
end
和控制器创建这样的动作:
def create
@club = Club.new(params[:club])
@club.user_id = current_user.id
respond_to do |format|
if @club.save
format.html { redirect_to @club, notice: 'Club was successfully created.' }
format.json { render json: @club, status: :created, location: @club }
else
format.html { render action: "new" }
format.json { render json: @club.errors, status: :unprocessable_entity }
end
end
end
认证是由设计gem完成的。另外让我困惑的是,如果我在heroku上运行rails控制台,它会说:
irb(main):001:0> Club
=> Club(id: integer, name: string, created_at: datetime, updated_at: datetime, user_id: integer)
所以即使是DB也应该是正确的。谢谢你的帮助!
在控制器中尝试一下,看看是否有效:
@club = current_user.clubs.build params[:club]
代替
@club = Club.new(params[:club])
@club.user_id = current_user.id
确保User
包含has_many :clubs
,然后可以去掉attr_accessible :user_id