措辭十足,但我很困惑。Rails 5 Model.where(user_id) - 兩個級別向上
我有一個User
模型誰has_many Clients
和has_many statements, through: :clients
然後statements
這belongs_to clients
和belongs to user
在控制檯我可以做任何我想要的查詢。 User.statements
User.client.first.statements
等等 - 我正在掙扎是Controller restrictions
現在很簡單 - 用戶應該只能夠看到Clients
和Statements
在他們自己。
對於客戶我做 客戶機控制器
def index
@clients = Client.where(user_id: current_user.id)
end
這似乎很好地工作。客戶端有一個用於user_id的字段
我很困惑如何模擬這個語句。語句不 - 沒有user_id字段。我不太確定我是否也想要它們,因爲在不久的將來,我希望客戶端belongs_to_many
:用戶和語句不受限制。
聲明控制器
def index
@clients = Client.where(user_id: current_user.id)
@statements = Statement.where(params[:client_id])
end
我只是真的不知道要放什麼東西 - 我知道params[:client_id]
沒有任何意義,但什麼是實現這一正確的方法是什麼?我是否以一種不安全的方式去做?
客戶端模式
class Client < ApplicationRecord
has_many :statements
has_many :client_notes, inverse_of: :client
belongs_to :user
validates :name, presence: true
validates :status, presence: true
accepts_nested_attributes_for :client_notes, reject_if: :all_blank, allow_destroy: true
end
聲明模型研究
class Statement < ApplicationRecord
belongs_to :client
belongs_to :user
validates :name, presence: true
validates :statement_type, presence: true
validates :client_id, presence: true
validates :start_date, presence: true
validates :end_date, presence: true
end
用戶模型
class User < ApplicationRecord
has_many :clients
has_many :statements, through: :clients
end
下面我提供的答覆正在使用
def index
if params[:client][:user_id] == @current_user.id
@clients = Client.includes(:statements).where(user_id: params[:client][:user_id])
@statements = @clients.statements
else
return 'error'
end
end
不能確定這是否是邏輯正確
你可以添加模型來查看他們的關係嗎? –
@SebastiánPalma完成。 – DNorthrup
爲什麼投票反對? – DNorthrup