【问题标题】:Add current_user Devise to Mongoid relations将 current_user 设计添加到 Mongoid 关系
【发布时间】:2011-10-18 19:24:14
【问题描述】:

大家好,我在 Mongoid 中有一个关系,我无法将 current_user 添加到此关系中以获取创建交易的用户。与 3 模型的关系。

我有三个模型 user.rb、house.rb 和 deal.rb

user.rb 关系(设计模型)

# Relationships
has_many :houses, dependent: :destroy
has_many :deals, dependent: :destroy
key :title

house.rb

# Relationships
 belongs_to :user
 embeds_many :deals

deal.rb

# Relationships
 embedded_in :house, :inverse_of => :deals
 belongs_to :user

在我的 routes.rb

 resources :houses do
  resources :deals
 end

在我的 house_controller.rb 的 create 方法中,我为这边的每个房子获取 current_user:

def create
   #@house = House.new(params[:house])
   @house = current_user.houses.new(params[:house])
    respond_to do |format|
      if @house.save
        format.html { redirect_to @house, notice: 'House was successfully created.' }
        format.json { render json: @house, status: :created, location: @house }
      else
        format.html { render action: "new" }
        format.json { render json: @house.errors, status: :unprocessable_entity }
      end
    end
  end

在我的 deals_controller.rb 我有创建的方法:

    def create 
      @house = House.find_by_slug(params[:house_id])
      @user = User.find(:user_id)
      @deal = @house.deals.create!(params[:deal])
      redirect_to @house, :notice => "Comment created!" 
    end

如何将创建交易的 current_user 添加到最后一个方法中?

【问题讨论】:

    标签: ruby-on-rails mongodb devise mongoid


    【解决方案1】:

    您可以简单地将这两行添加到创建操作中:

    @deal.user=current_user
    @deal.save
    

    而且我还建议您不要使用 create!相反,您应该在脚手架创建操作中使用 .new 和 .save ! ;)

    【讨论】:

    • 谢谢!我有更改创建新并保存:D。但是对于 house.rb 中的“embeds_many :deals”和 deal.rb 中的“embedded_in :house, :inverse_of => :deals”,显示错误“通过关系关联从用户文档引用 a(n) 交易文档不是允许,因为该交易已嵌入。”但是 has_many 和 belongs_to 工作正常。最好使用 embeds_many 或 has_many 和引用?谢谢
    • 如果有人遇到这种情况,为了避免@hyperrjas 看到的错误,即“由于嵌入了交易,因此不允许通过关系关联从用户文档中引用(n)交易文档。 "只需从他在第一个问题中定义的 user.rb 中删除这一行 #has_many :deals,dependent: :destroy
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-07
    • 1970-01-01
    相关资源
    最近更新 更多