Jump to content

The ultimate community for Ruby on Rails developers.


Photo

Rails association has_many controller setup


  • Please log in to reply
1 reply to this topic

#1 kalubalu

kalubalu

    Passenger

  • Members
  • 1 posts

Posted 15 July 2014 - 05:07 AM

Hey all, 

 

I am currently new to rails and I am working on a sample app that has_many :friend_request and belongs_to :user. for example:

model

class User < ActiveRecord::Base

has_many :friend_requests

end



class FriendRequest < ActiveRecord::Base

belongs_to :user

belongs_to :friend

end



class Friend < ActiveRecord::Base

has_many :friend_requests

end

and db contains the following:


class CreateFriendRequests < ActiveRecord::Migration
  def change
    create_table :friend_requests do |t|
      t.references :user, index: true
      
      t.timestamps
    end
  end
end
I have a user db with information regarding the user in a separate migration.
 
 
I was wondering how I can link them together so when a user clicks a link, they are now connected with one another. As in, are they already linked together and what would the controller look like? Can someone help? Thank you in advance!


#2 Ohm

Ohm

    Driver

  • Moderators
  • 421 posts
  • LocationCopenhagen

Posted 15 July 2014 - 06:36 AM   Best Answer

Yes, they are already linked together, that is to say, a FriendRequest object has a user method and vice versa.

 

You need to create the actual link between objects yourself in the controller. Something like:

class FriendRequestsController < ApplicationController
  ...

  def add_friend
    @user = User.find(params[:user_id])
    @friend = Friend.find(params[:friend_id])
    friend_request = FriendRequest.new(user: @user, friend: @friend)

    if friend_request.save
      # It got saved, now render what ever you'd like
    else
      # It didn't get saved, possibly because of validations or db constraints
      # render an error
    end
  end

  ...
end

Remember to set this up in your routes.rb-file and you're good to go.


Blog: http://ohm.sh | Twitter: @madsohm | Work: Lokalebasen.dk





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users