简体   繁体   English

创建一个新对象时,不能使用Emirates_to / has_many关系设置user_id字段

[英]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.

相关问题 我怎样才能使用户具有has_many个对象,但每个对象都可以属于许多用户? - How can I make a user has_many objects but each object can belong_to MANY users? 在Ruby on Rails中,模型“ has_many”和“ belong_to”如何使用除主ID之外的其他字段? - In Ruby on Rails, how can a model “has_many” and “belong_to” using a different field other than primary ID? Rails为多个主键在belong_to和has_many之间设置了基于角色的关系 - Rails set role based relationship between belong_to and has_many for multiple primary keys 用户has_many:课程,但课程不属于:用户 - user has_many :courses, but course doesn't belong_to :user 数据库关联,类has_many和belonge_to可以属于同一对象吗? - Database Association, Can a class has_many and belong_to the same object? has_many和belong_to关联出现问题,找不到方法 - Issue with has_many and belong_to association, can't find method Rails has_many / belong_to协会 - Rails has_many/belong_to Associations 在rails中的has_many中的关联 - Associations in has_many , belong_to in rails 关于belong_to,has_one,has_many的困惑 - Confusion regarding belong_to, has_one, has_many 如何在ruby中为用户和任务模型之间的has_many,belong_to关联创建迁移脚本 - How to create migration script for has_many, belong_to association between user and task model in ruby
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM