这些是我的协会:
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
这些是我所做的更改,因此关联正常工作:
所有型号的表格都包含user_id。
我把关联内部放在上面。
我使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
答案 0 :(得分:3)
您可能需要通过用户创建业务,或者在保存时在控制器中分配user_id。
例如:current_user.businesses.create(params[:business])
而不是Business.create(params[:business])
OR
Business.create(params[:business].merge(:user => current_user))
要确保传入所有属性,请使用
行的验证validates_presence_of :user_id
在具有此数据列的模型
上