[英]Can't set user_id field when creating a new object, using a belong_to / has_many relationship
Using rails 3.2 & ruby 2.1 使用Rails 3.2和ruby 2.1
Here my models 这是我的模特
class CheckoutRent < ActiveRecord::Base
attr_accessible :comment, :rent_id, :user_id
belongs_to :user
belongs_to :rent
end
class User < ActiveRecord::Base
has_many :checkout_rent
...
end
My controller 我的控制器
class CheckoutRentsController < InheritedResources::Base
def new
if user_signed_in?
@checkout_rent = current_user.checkout_rent.new
@checkout_rent.save
else
redirect_to new_user_session_path, notice: 'Veuillez vous connecter.'
end
end
end
My views 我的看法
= form_for(@checkout_rent) do |f|
.field
= f.select :rent_id, Rent.all.collect{|c| [c.user.name, c.id]}
.field
= f.label :comment
%br/
= f.text_field :comment
.actions
= f.submit
All is fine except that user_id is not set when creating a new checkout_rent. 一切正常,除了在创建新的checkout_rent时未设置user_id之外。
In console: CheckoutRent.last.user_id return nil 在控制台中:CheckoutRent.last.user_id返回nil
Your user model has_many checkout_rent, so in your controller you should have: 您的用户模型has_many checkout_rent,因此在您的控制器中,您应该具有:
@checkout_rent = current_user.checkout_rents.create
note the plural checkout_rents (as you have it now it should fail), also note that create replaces new + save, so you can erase this line: 注意复数的checkout_rents(现在应该失败了),还要注意create替换了new + save,因此您可以删除以下行:
@checkout_rent.save
EDIT: 编辑:
I also suggest you modify the following line to follow the conventions: 我还建议您修改以下行以遵循约定:
has_many :checkout_rents
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.