2012-06-09 26 views
0

這是我協會:爲什麼我添加更多模型時突然沒有分配user_id?

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. 我做了黃燦燦的能力反映這些變化

    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 
    

我使用的設計,如果它有助於瞭解。

當我想創建一個商業,它讓我但他們沒有分配的用戶。我失去了什麼問題。我以爲它會像以前一樣自動分配自己,因爲用戶只有很多價格。你認爲問題是什麼?

編輯


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

你跑什麼代碼到cr吃掉生意? – cdesrosiers

回答

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 

的車型線有這個數據列

+1

也許''current_user.businesses.create(params [:business])''和'Business.create(params [:business] .merge(:user => current_user))'?看一看:http://stackoverflow.com/questions/7128214/rails-3-how-to-add-user-id-current-user-id-assotiations –

+0

正如米哈伊爾D引用後,你應該將用戶設置在控制器中,而不是通過參數分配。否則有人可以僞造一個請求並假裝成一個隨機用戶。 – jagse

+0

,但它通過康康控制角色......所以這不應該是一個問題 –

相關問題