问题
I'm not sure if my question is worded correctly.
I have three models: User
, Item
, and UserItem
.
user has_many :user_items
user has_many :items, through :user_items
item has_many :user_items
item has_many :users -> {uniq}, through :user_items
item belongs_to :user
user_item belongs_to :user
user_item belongs_to :item
I need a way to see if a user has an item to make if
statements in my item views But here's the catch, user_items have enum status: [ :pending, approved]
. So I need to see if a current_user
has a certain :pending
item.
For example when a user visits item1's view page I have the item_controller's show action declare @item = Item.find_by_id(params[:id])
. But then what can I do with this @item
to see if a user has this item?
回答1:
Try:
current_user.items.exists?(params[:id])
Or
current_user.items.exists?(@item.id)
回答2:
But then what can I do with this @item to see if a user has this item?
I think what you are missing here is model methods. For example, if you added a method to the Item model called belongs_to_user_in_pending_state, you'd be able to call @item.belongs_to_user_in_pending_state(current_user)
anywhere you need it.
def belongs_to_user_in_pending_state(user)
if self.user_items.pending.select {|s| s.user == user}.count > 0
return true
else
return false
end
end
回答3:
Extending @lei-liu's answer here. One can find if the record exists among the many or not, through: current_user.items.exists?(params[:id])
At the same time, exists?
allows one to filter through the columns besides id
, and also allows for more complicated conditions, like the following:
current_user.items.exists?('id > 3')
current_user.items.exists?(name: 'some_name')
回答4:
1) Add a scope to User_item class
scope :pending, -> {where status: 'pending'}
2) Use that scope in an instance method of Item class:
def is_pending_with_someone?
self.user_items.pending.count > 0
end
Then you can use
if @item.is_pending_with_someone?
...
来源:https://stackoverflow.com/questions/36490579/rails-check-if-record-exists-in-has-many-association