Get data from database with two conditions in one list - ruby-on-rails

I'm new to this. I have a (sqlite3, but with ActiveRecord it doesn't matter) table called Messages and a model called Message. I want to find all messages in database that have user_id or reciever_id equal to the object user and his attribute id (for short user.id). I know it's probably just one simple line of code, but I wanna do it the right "rails" way and I don't have much experience with this.
I'm using Rails 3. Thanks for any help.
Cheers

I suspect that what you will want this relationship in many places in your code, and actually this represents a fundamental part of your application's design.
Conceptually a 'message' belongs to a 'sender' and also to a 'receiver'. In reverse, a 'user' has many messages that she has sent, and many messages that she has received.
in the Message model, add the following
belongs_to :user
belongs_to :receiver, :class_name => "User"
in the User model, add the following
has_many :messages
has_many :sent_or_received_messages, :class_name => "Message", :conditions => ["user_id = ? OR receiver_id = ?", id, id])
Now you can do this:
my_user.messages # all of the messages the user has sent
my_message.user # the user who sent the message
my_message.receiver # the user who received the message
my_user.sent_or_received_messages # all messages where the user was a sender or a receiver

I'm assuming that you mean a user has_many :messages....
# assuming you are looking for a particular user
Message.where(['user_id=? OR receiver_id=?', user.id, user.id])

Related

Rails associations for a fairly simple notification system

I'm trying to set up a notification system in Rails, along with mongoid (but I don't think this is mongoid specific).
The basic structure is like this - Every notification has a notifier (the one who is responsible for the notification) and a notifee (the one who receives the notification). When a user A comments on user B's post (in a blog system for example), the User A becomes the notifier and the User B is the notifiee.
User.rb
# nothing in here
Notification.rb
has_one :notifier, :class_name => "User"
belongs_to :notifiee, :class_name => "User"
However, when I do:
#notification = Notification.new
#notification.notifier = current_user
#notification.notifiee = User.first #Just for the sake of the example
#notification.save
I get this error:
Problem: When adding a(n) User to Notification#notifier, Mongoid could
not determine the inverse foreign key to set. The attempted key was
'notifiee_id'.Summary: When adding a document to a relation, Mongoid
attempts to link the newly added document to the base of the relation
in memory, as well as set the foreign key to link them on the database
side. In this case Mongoid could not determine what the inverse
foreign key was.Resolution: If an inverse is not required, like a
belongs_to or has_and_belongs_to_many, ensure that :inverse_of => nil
is set on the relation. If the inverse is needed, most likely the
inverse cannot be figured out from the names of the relations and you
will need to explicitly tell Mongoid on the relation what the inverse
is.
What could I be doing wrong? Or, is there a better way to model this??
Any help is much appreciated! Thank you.
You should probably go for the following associations:
User:
has_many :notifications_as_notifier, :class_name=>'Notification', :foreign_key=>'notifier_id'
has_many :notifications_as_notifiee, :class_name=>'Notification', :foreign_key=>'notifiee_id'
Notification:
belongs_to :notifier, :class_name=>'User', :foreign_key=>'notifier_id'
belongs_to :notifiee, :class_name=>'User', :foreign_key=>'notifiee_id'
Your notifications table should have notifier_id and notifiee_id.
Now you can do,
#notification = Notification.new
#notification.notifier = current_user
#notification.notifiee = User.first #Just for the sake of the example
#notification.save
What I find questionable in your setup:
You have,
has_one :notifier, :class_name => "User"
belongs_to :notifiee, :class_name => "User"
When you use has_on, then the other relation (table) must have a foreign key referencing the parent. Here users must have a column notification_id or something. This is impractical because a single user has many notifications (based on your explanations).
Secondly, you are associating Notification to User through two relationships but you are mentioning anything about the foreign key to use to enforce the association.
And why do you not have an inverse relation in the User model? Would it not help if you had access to something like: current_user.notifications_as_notifier ??

How do I specify 2 foreign keys in a model in ruby on rails?

I'd like to be able to access current_users conversation with ease.
E.G.
current_user.conversations
The thing is the current user can either be a sender or recipient (sender_id or recipient_id)
class User < ActiveRecord::Base
has_many :conversations, :foreign_key => "sender_id"
This works but there are times when a sender is a recipient or say for example someone has sen t someone 10 messages as a sender and the recipient hasn't replied to any but still a conversation exists in the database for them.
If I was logged in as that user and typed current_user.conversations nothing would come up because the foreign key specified in the user model is sender_id. Isn't there a way to specify both? Like using "OR" in sql?
Kind regards
I don't believe there is a way to do exactly what you want, but there are a few alternate approaches you may want to consider:
1) Splitting it up into two relationships, sent_conversations and received_conversations, and then you can define a method which combines them.
2) Adding a new class method that does some custom SQL:
class User < ActiveRecord::Base
def conversations
Conversation.where("sender_id = :id OR receiver_id = :id", id: self.id)
end
end

Including an association if it exists in a rails query

Update: This may be something that just isn't doable. See this
TLDR: How do you conditionally load an association (say, only load the association for the current user) while also including records that don't have that association at all?
Rails 3.1, here's roughly the model I'm working with.
class User
has_many :subscriptions
has_many :collections, :through => :subscriptions
end
class Collection
has_many :things
end
class Thing
has_many :user_thing_states, :dependent => :destroy
belongs_to :collection
end
class Subscription
belongs_to :user
belongs_to :collection
end
class UserThingState
belongs_to :user
belongs_to :thing
end
There exist many collections which have many things. Users subscribe to many collections and thereby they subscribe to many things. Users have a state with respect to things, but not necessarily, and are still subscribed to things even if they don't happen to have a state for them. When a user subscribes to a collection and its associated things, a state is not generated for every single thing (which could be in the hundreds). Instead, states are generated when a user first interacts with a given thing. Now, the problem: I want to select all of the user's subscribed things while loading the user's state for each thing where the state exists.
Conceptually this isn't that hard. For reference, the SQL that would get me the data needed for this is:
SELECT things.*, user_thing_states.* FROM things
# Next line gets me all things subscribed to
INNER JOIN subscriptions as subs ON things.collection_id = subs.collection_id AND subs.user_id = :user_id
# Next line pulls in the state data for the user
LEFT JOIN user_thing_states as uts ON things.id = uts.thing_id AND uqs.user_id = :user_id
I just don't know how to piece it together in rails. What happens in the Thing class? Thing.includes(:user_thing_states) would load all states for all users and that looks like the only tool. I need something like this but am not sure how (or if it's possible):
class Thing
has_many :user_thing_states
delegates :some_state_property, :to => :state, :allow_nil => true
def state
# There should be only one user_thing_state if the include is correct, state method to access it.
self.user_thing_states.first
end
end
I need something like:
Thing.includes(:user_question_states, **where 'user_question_state.user_id => :user_id**).by_collections(user.collections)
Then I can do
things = User.things_subscribed_to
things.first.some_state_property # the property of the state loaded for the current user.
You don't need to do anything.
class User
has_many :user_thing_states
has_many :things, :through => :user_thing_states
end
# All Users w/ Things eager loaded through States association
User.all.includes(:things)
# Lookup specific user, Load all States w/ Things (if they exist for that user)
user = User.find_by_login 'bob'
user.user_thing_states.all(:include => :things)
Using includes() for this already loads up the associated object if they exist.
There's no need to do any filtering or add extra behavior for the Users who don't have an associated object.
Just ran into this issue ourselves, and my coworker pointed out that Rails 6 seems to include support for this now: https://github.com/rails/rails/pull/32655
*Nope, didn't solve it :( Here's a treatment of the specific issue I seem to have hit.
Think I've got it, easier than expected:
class Thing
has_many :user_thing_states
delegates :some_state_property, :to => :state, :allow_nil => true
scope :with_user_state, lambda { |user|
includes(:user_thing_states).where('user_thing_states.user_id = :user_id
OR user_thing_states.user_id IS NULL',
{:user_id => user.id}) }
def state
self.user_thing_states.first
end
end
So:
Thing.with_user_state(current_user).all
Will load all Things and each thing will have only one user_question_state accessible via state, and won't exclude Things with no state.
Answering my own question twice... bit awkward but anyway.
Rails doesn't seem to let you specify additional conditions for an includes() statement. If it did, my previous answer would work - you could put an additional condition on the includes() statement that would let the where conditions work correctly. To solve this we'd need to get includes() to use something like the following SQL (Getting the 'AND' condition is the problem):
LEFT JOIN user_thing_states as uts ON things.id = uts.thing_id AND uqs.user_id = :user_id
I'm resorting to this for now which is a bit awful.
class User
...
def subscribed_things
self.subscribed_things_with_state + self.subscribed_things_with_no_state
end
def subscribed_things_with_state
self.things.includes(:user_thing_states).by_subscribed_collections(self).all
end
def subscribed_things_with_no_state
Thing.with_no_state().by_subscribed_collections(self).all
end
end

Rails/ActiveRecord: has_one, belongs_to and before_create

I'm having trouble figuring out how best to model my data. I have the following two models in my Rails application:
class Foo < ActiveRecord::Base
belongs_to :active_bar, :class_name => 'Bar'
accepts_nested_attributes_for :active_bar
before_create do |f|
f.active_bar.foo = f
# Causes stack overflow!
f.active_bar.save!
end
end
class Bar < ActiveRecord::Base
belongs_to :foo
end
test 'create with nested attributes' do
f = Foo.create!(:name => 'foo-name', :active_bar_attributes => {:name => 'bar-name'})
assert_equal 'foo-name', f.name
assert_equal 'bar-name', f.active_bar.name
assert_equal f, f.active_bar.foo
f_id = f.to_param
retrieved_f = Foo.find_by_id!(f_id)
assert_equal retrieved_f, retrieved_f.active_bar.foo
end
What you probably think is strange is the reflexive belongs_to relationship I'm attempting to model. My plan is that, eventually, Foo will have many instances of Bar while one instance will be considered "active". Thus I'm using active_bar to refer to this active instance. The problem with this code is that I need to set the foo property in Bar back to the parent Foo instance and I can't figure out the best place to do it (the save! call in before_create ends up being recursive and overflowing the stack) or even if this is the cleanest way to model this type of relationship.
Essentially I'm attempting to model a user (equivalent to Foo) who has multiple e-mail addresses (equivalent to Bar) with one of the e-mail addresses marked as the user's primary address.
Any advice?
I'm just going to respond in terms of User and EmailAddress if that's okay with you ;)
In your User model should really be has_many :email_addresses, has_one :active_email, :class_name => 'EmailAddress' and, as you correctly identified, accepts_nested_attributes_for :email_addresses
The EmailAddress model should then, of course, have belongs_to :User.
Aside from these, I think you are over-thinking things. In the form to create a user, then, allow them to enter as many email addresses as they want and either have them put their "active" email first, or have some sort of toggle to denote which email address is their primary address.
Edit: As far as the before_create statement, I think it only needs to be a simple validation that a primary email address has been given/marked (if it is necessary that they specify an email address in the first place).
If this doesn't fulfull what functionality you need, please comment. I'll try and help more.

writing an attribute to my through table with validation?

I have been trying to do this for ages and can seem to grasp it. hope someone can help ?
i have a 'message' model that has many through 'distribute' relationship to a 'contact_detail' model.
basically a message can have many contacts associated with it and a contact can have many messages.
I can get this to work and save it succesfully but i want also have a creater attribute on the 'distribute' model that i want to set to true for the creater of the message.
my form params are as follows :
{"message"=>{"message"=>"a great message ...",
"messagable_id"=>"58",
"title"=>"how are you ?",
"messagable_type"=>"MachineEnquiry",
"message_type_id"=>"1",
"contact_detail_ids"=>["2",
"2",
"11",
"7"]},
"commit"=>"Send message",
"datetime"=>""}
The 'distributes' model has a contact_detail_id' attribute and this is all saving but before save i want to set the create attribute along with a contact_detail_id.
I can so this after save but i want to validate that the creater has been set so i have to do this before save dont i ? and not sure how to do this.
Any ideas? hopefully someone can help ?
thanks in advance
rick
From the way you describe things, creator should the same for every distribution record associated with a particular message. Making much more sense to save add a new column and belongs_to relationship to Message.
class Message < ActiveRecord::Base
belongs_to :creator, :class_name => "User" # links creator to your User model
validates_presence_of :creator_id # ensures creator_id is not empty
...
end
Filling that field from the form is as simple as adding
<%= f.hidden_field :creator_id, current_user.id %>
If I'm wrong in assuming that distribution record for the same message will have the same creator, then you should look into accepts_nested_attributes_for to pass details to related models from a form.

Resources