【问题标题】:Why is the user_id suddenly not being assigned when I add more models?为什么添加更多模型时突然没有分配user_id?
【发布时间】:2012-06-09 06:40:12
【问题描述】:

这些是我的联想:

class User
 has_many :products
 has_many :prices
 has_many :businesses
 has_many :stores
end

class Price
 belongs_to :store
 belongs_to :user
 belongs_to :product
end

class Store
  belongs_to :user
  belongs_to :business
  has_many :prices
end

class Business
  belongs_to :user
  has_many :stores
end

class Product
  belongs_to :user
  has_many :prices
end

这些是我所做的更改,以便关联正常工作:

  1. 所有模型的表中都有 user_id。

  2. 我像上面一样把关联放在里面。

  3. 我让 CanCan 的能力反映了这些变化

    def initialize(user)
      if user.role == "admin"
        can :manage, :all
      elsif user.role == "default"
        can :manage, [Price, Store, Business, Product], :user_id => user.id
        can :read, [Product, Store, Business, Price]
      end
    end
    

如果有帮助,我正在使用 Devise。

当我想创建一个企业时,它允许我,但他们没有分配用户。我不知道是什么问题。我认为它会自动分配自己,就像以前用户有很多价格时一样。您认为问题出在哪里?

编辑


class BusinessesController < ApplicationController
  before_filter :authenticate_user!
  load_and_authorize_resource

  def show
    @business = Business.find(params[:id])
  end

  def new
    @business = Business.new
  end

  def create
    @business = Business.new(params[:business])
    if @business.save
      redirect_to new_business_path, :notice => "Successfully added."
    else
      render :new, :notice => "It seems there was an error. Please try again."
    end
  end
end

【问题讨论】:

  • 您正在运行什么代码来创建业务?

标签: ruby-on-rails ruby ruby-on-rails-3 devise cancan


【解决方案1】:

您可能需要通过用户创建业务或在保存时在控制器中分配user_id。

例如:current_user.businesses.create(params[:business]) 而不是 Business.create(params[:business])

Business.create(params[:business].merge(:user => current_user))

为了确保您的所有属性都被传入,请使用类似于

的验证
validates_presence_of :user_id

在具有此数据列的模型上

【讨论】:

  • 可能是current_user.businesses.create(params[:business])Business.create(params[:business].merge(:user =&gt; current_user))?看看:stackoverflow.com/questions/7128214/…
  • 正如 Mikhail D 引用的帖子中提到的,您应该在控制器中设置用户,而不是通过参数分配它。否则有人可以伪造请求并伪装成随机用户。
  • 但它通过 cancan 进行角色控制...所以这应该不是问题
  • @MikhailD 谢谢你,更新和支持...,jagse,角色是通过 cancan 管理的,这仍然是个问题吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-13
  • 2014-03-31
  • 1970-01-01
  • 2015-06-09
  • 1970-01-01
  • 2013-06-24
  • 1970-01-01
相关资源
最近更新 更多