Rails - Create/Destroy record in join table - ruby-on-rails

I'm working on this record insert/delete I'm not sure what the syntax is to perform the query.
I have a user model and an event model. I have created a joining table called Personal that stores the user_id, and event_id of any events that the users like.
I created an "Add" method in my events controller so whenever someone clicks it run to that and perform the create logic I'm trying to develop now.The action is tied to a extra column I added to the grid displaying all the events.
The user model =>
has_many :personals
The event model =>
has_many :personals
The personal model =>
belongs_to :user
belongs_to :events
I thought it would be something like =>
#user = User.find(session[:user_id])
#event = Event.find(params[:id])
# Personal.new = User.Event?
can anyone help?

If you're using a has_and_belongs_to_many association, which would be unfortunate, removing the associated links can be tricky as there's no identifier for each link.
Using a has_many :through relationship is much easier to maintain and will allow you to do simple things like:
class User < ActiveRecord::Base
has_many :user_events
has_many :events,
:through => :user_events
end
#user.events.delete(#event)
This doesn't remove the Event itself, that'd require an Event#destroy call, but the join record that links the two.

Related

Many to Many relation issue in Rails 4

I am a rails beginner and encountered the following issue
Models are setup as follows (many to many relation):
class Activity < ActiveRecord::Base
belongs_to :user
has_many :joinings
has_many :attendees, through: :joinings
end
class Joining < ActiveRecord::Base
belongs_to :activity
belongs_to :attendee
end
class Attendee < ActiveRecord::Base
has_many :joinings
has_many :activities, through: :joinings
end
This is one page test application for some users posting some activities, and other users to join the activities.
It is organized as single page format (activities index), and after each activity, there is a "Join" button users can click.
I am stuck at the point when a user needs to join a specific activity.
in the index.html.erb (of the activities), with the Join button code.
This will point to the attendee controller, to Create method, but I got no information regarding the Activity that I want to follow (eg. activity_id, or id)
Without this I cannot use the many to many relation to create the attendee.
What would be the correct button code, or any other suggestion to to get the corresponding activity ID in the attendees controller?
I tried a lot of alternatives, including even session[current_activity] , but is pointing (of course) always to the last activity.
Thanks so much !
If you have existing activities, and existing attendees, and you want to change the relationship between them, then you are editing the join table records. Therefore, you should have a controller for these. Like i said in my comment i'd strongly recomnmend renaming "joining" to "AttendeeActivity" so your schema looks like this:
class Activity < ActiveRecord::Base
belongs_to :user
has_many :attendee_activities
has_many :attendees, through: :attendee_activities
end
class AttendeeActivity < ActiveRecord::Base
belongs_to :activity
belongs_to :attendee
end
class Attendee < ActiveRecord::Base
has_many :attendee_activities
has_many :activities, through: :attendee_activities
end
Now, make an AttendeeActivitiesController, with the standard scaffoldy create/update/destroy methods.
Now, when you want to add an attendee to an activity, you're just creating an AttendeeActivity record. if you want to remove an attendee from an activity, you're destroying an AttendeeActivity record. Super simple.
EDIT
If you want to create an Attendee, and add them to an activity at the same time, then add a hidden field to the form triggered by the button:
<%= hidden_field_tag "attendee[activity_ids][]", activity.id %>
This will effectively call, when creating the attendee,
#attendee.activity_ids = [123]
thus adding them to activity 123 for example.
You have several options here. I'm assuming that the Join button will simply submit a hidden form to the attendees controller's create action. So the simplest solution would be to include the activity_id as a hidden form tag that gets submitted along with the rest of the form. This activity_id will be available in the params hash in the controller.
The other option is to setup Nested routing so that the activity_id is exposed via the path.
Thanks for all the details. I will change the naming of the join table for the future.
My problem was that I could not find the specific activity for attendee create method. Finally I found something like this for the JOIN button:
<%= button_to 'Join', attendees_path(:id => activity) %>
This will store the Activity ID, so I am able to find it in the Attendees controller:
def create
activity = Activity.find(params[:id])
#attendee = activity.attendees.create user_id: current_user.id
redirect_to activities_path
end
this updates also the Joinings (AttendeeActivity) table.
I will study about the hidden_field_tag solution, as is not clear to me yet.

Retrieve data from join table

I am new in RoR and I am trying to write a query on a join table that retrieve all the data I need
class User < ActiveRecord::Base
has_many :forms, :through => :user_forms
end
class Form < ActiveRecord::Base
has_many :users, :through => :user_forms
end
In my controller I can successfully retrieve all the forms of a user like this :
User.find(params[:u]).forms
Which gives me all the Form objects
But, I would like to add a new column in my join table (user_forms) that tells the status of the form (close, already filled, etc).
Is it possible to modify my query so that it can also retrieve columns from the user_forms table ?
it is possible. Once you've added the status column to user_forms, try the following
>> user = User.first
>> closed_forms = user.forms.where(user_forms: { status: 'closed' })
Take note that you don't need to add a joins because that's taken care of when you called user.forms.
UPDATE: to add an attribute from the user_forms table to the forms, try the following
>> closed_forms = user.forms.select('forms.*, user_forms.status as status')
>> closed_forms.first.status # should return the status of the form that is in the user_forms table
It is possible to do this using find_by_sql and literal sql. I do not know of a way to properly chain together rails query methods to create the same query, however.
But here's a modified example that I put together for a friend previously:
#user = User.find(params[:u])
#forms = #user.forms.find_by_sql("SELECT forms.*, user_forms.status as status FROM forms INNER JOIN user_forms ON forms.id = user_forms.form_id WHERE (user_forms.user_id = #{#user.id});")
And then you'll be able to do
#forms.first.status
and it'll act like status is just an attribute of the Form model.
First, I think you made a mistake.
When you have 2 models having has_many relations, you should set an has_and_belongs_to_many relation.
In most cases, 2 models are joined by
has_many - belongs_to
has_one - belongs_to
has_and_belongs_to_many - has_and_belongs_to_many
has_and_belongs_to_many is one of the solutions. But, if you choose it, you must create a join table named forms_users. Choose an has_and_belongs_to_many implies you can not set a status on the join table.
For it, you have to add a join table, with a form_id, a user_id and a status.
class User < ActiveRecord::Base
has_many :user_forms
has_many :forms, :through => :user_forms
end
class UserForm < ActiveRecord::Base
belongs_to :user
belongs_to :form
end
class Form < ActiveRecord::Base
has_many :user_forms
has_many :users, :through => :user_forms
end
Then, you can get
User.find(params[:u]).user_forms
Or
UserForm.find(:all,
:conditions => ["user_forms.user_id = ? AND user_forms.status = ?",
params[:u],
'close'
)
)
Given that status is really a property of Form, you probably want to add the status to the Forms table rather than the join table.
Then when you retrieve forms using your query, they will already have the status information retrieved with them i.e.
User.find(params[:u]).forms.each{ |form| puts form.status }
Additionally, if you wanted to find all the forms for a given user with a particular status, you can use queries like:
User.find(params[:u]).forms.where(status: 'closed')

Proper Usage of Rails After_Filter

In a small app I am building, I have a controller that creates an exchange. When a user creates an exchange they are simultaneously the organizer of the exchange and a participant in the exchange. Participants are tracked by a join table that joins a user_id and an exchange_id. Organizers are tracked by a foreign user_id key in the exchange table.
I am trying to figure out where to put the code that will automatically create a new membership record for the organizer of the exchange. Should I put this in the exchange_controller's create action itself, or in an after_filter triggered by the create action? Or maybe somewhere else? Part of the problem is that I could not find any good examples of proper after_filter use (guides.rubyonrails.org only had sparse mention of it), so any links pointing in the correct direction would be appreciated as well.
Here is relevant model code:
app/models/user.rb:
# Returns array of exchanges user is participating in
has_many :participations,
:through => :memberships,
:source => :exchange
# Returns array of exchanges user has organized
has_many :organized_exchanges,
:foreign_key => :organizer_id,
:class_name => "Exchange"
app/models/membership.rb:
class Membership < ActiveRecord::Base
attr_accessible :exchange_id, :user_id, :role
belongs_to :exchange
belongs_to :user
end
app/modles/exchange.rb:
belongs_to :organizer,
:foreign_key => :organizer_id,
:class_name => "User"
has_many :memberships, :dependent => :destroy
has_many :participants,
:through => :memberships,
:source => :user
And here is the relevant controller code:
app/controllers/exchanges_controller.rb:
def create
#exchange = Exchange.new(params[:exchange])
#exchange.organizer_id = current_user.id
if #exchange.save
redirect_to exchange_path(#exchange.id)
else
render 'new'
end
end
after_filter is a completely different thing in this context. It is called when your view is completely processed and so you want to call some action to do something.
You can use after_create callback that is triggered when a record is created in the database.
In your case, a user is creating an exchange and so after the exchange is created, the after_create callback is triggered and you can apply your functionality over there to make the current user who created the exchange to be a participant.
The way to write in a model is like this:
after_create :do_something
def do_something
something.do!
end
Note: It is not good to use after_save here because it is triggered every time you save a record or even if you update a record.
There is a nice SO post that clearly tells you the difference between the after_create and after_save.
See this SO post for the difference between the two.
More on the callbacks is here.

Rails model relationship, has many and belongs to many?

I have the following structure:
class User < ActiveRecord::Base
end
class Item < ActiveRecord::Base
end
class Group < ActiveRecord::Base
end
A User can create (and thereby own) a Group.
A Group is a list of Items and a list of the Users who can access these items.
In other words, a user has a list of Items and can control which Users can see these items through the Group membership.
How should I set up the relationship?
Well, you're going to run into some issues with the fact that you want a double many-to-many relationship here. Ie. groups have and belong to many items, and items have and belong to many users.
So, I would setup the relationship this way, assuming you want a group to be able to have many items, and items may belong to more than one group:
User has_many :groups
User has_and_belongs_to_many :items
User has_many :own_items, :class_name => 'Item'
Group belongs_to :user
Group has_and_belongs_to_many :items
Item has_and_belongs_to_many :groups
Item has_and_belongs_to_many :users
Item belongs_to :owner, :class_name => 'User'
Your migrations will need to look like so:
# Group
:user_id, :integer
# Item
:owner_id, :integer
# GroupsItems
:group_id
:item_id
#ItemsUsers
:item_id
:user_id
Now, the structure you're looking at isn't the cleanest in the universe, but it will behave as you expect as long as you're careful about the user association.
For instance, to create a user's item:
#user = User.first
#user.own_items.create(...)
To assign users as able to view an item...
#item = Item.find(...) #or #user.own_items.find(...)
#item.users = [user1,user2,user3]
Now, this sets up the relationships you want, but you'll have to also write your own controller / view logic to limit access, or use a library like CanCan.
For instance:
# View
- if #item.users.include?(current_user)
...show item...
# Items Controller:
def show
#item = Item.find(params[:id])
if #item.users.include?(current_user)
...continue...
else
redirect_to :back, :alert => 'You are not authorized to view this item.'
end
end
I hope those examples point you in the right direction. You'll have a number of issues to deal with relating to access control, but trying to think of them and solve each one I can think of is beyond the scope of this question.
Also, note that this is the simplest setup I could think of. If you have more complex logic in the associations you might want to make a full-fledged join model and use has_many :through associations instead of HABTM.
Good luck!

Simulating has_many :through with Mongoid

I'm trying to create an event platform using MongoDB as the db. I want a many-to-many relationship between Events and Users. The thing is, I want there to be properties in the relationship (e.g., Users can either be confirmed or unconfirmed for a specific Event). I realize this would be ideally suited for an RDBMS, but I'm using MongoDB for reasons that I'm taking advantage elsewhere and I would prefer to continue using it.
What I would like is for each Event to embed many Guests, which belong to Users. That way, I can see which users are attending an event quickly and with only one query. However, I would also like to see which Events a User is attending quickly, so I would like each User to have an array of Event ids.
Here is a code summary.
# user of the application
class User
has_many :events
end
# event that users can choose to attend
class Event
embeds_many :guests
has_many :users, :through => :guests # Won't work
end
# guests for an event
class Guest
field :confirmed?, type: Boolean
embedded_in :event
belongs_to :user
end
# Ideal use pattern
u = User.create
e = Event.create
e.guests.create(:user => u, :confirmed => true)
With the ideal use pattern, e has a Guest with a reference to u and u has a reference to e.
I know the has_many :through line won't work. Any suggestions as to how to get similar functionality? I was thinking of using an after_create callback in Guest to add a reference to the Event in User, but that seems pretty hacky.
Maybe I've gone down the wrong path. Suggestions? Thanks.
You can just store the event ids in a array on the user.
You have to manage the array when the event changes or the user is removed from the event for some reason. But that is the trade off.
User.events can then be found with a single db call.
Look at observers to manage the association.
I ended up using callbacks in the models to accomplish I wanted. Here's what it looks like.
Edit: I just saw nodrog's answer. Yeah, using observers would probably have been neater, I didn't know about them. Thanks!
# user of the application
class User
has_and_belongs_to_many :events, inverse_of: nil, dependent: :nullify
end
# event that users can choose to attend
class Event
embeds_many :guests
index 'guests.user_id', unique: true
before_destroy :cleanup_guest_references
def cleanup_guest_references
self.guests.each do |guest|
guest.destroy
end
end
end
# guests for an event
class Guest
field :confirmed?, type: Boolean
embedded_in :event, :inverse_of => :guests
belongs_to :user
after_create :add_event_for_user
before_destroy :remove_event_for_user
private
def add_event_for_user
self.user.events.push(self.event)
end
def remove_event_for_user
self.user.events.delete self.event
self.user.save
end
end

Resources