I have a user and group table. In user table I have id,name . In group table I have id group_name, created_by , user_id. Here a user can belong to more than one group but not the same group twice. A group can have many users but not the same user twice.
Here is my code.
group.rb
module Client
class Group < ActiveRecord::Base
has_many :users
end
end
user.rb
class User < ActiveRecord::Base
belongs_to :client_groups
end
Now when a user creates a new group, he should be automatically be persisted into the user_id and created_by field.
So as per the guides , I tried to follow the same with my code like this
#user.Client::Group.new(client_group_params)
but it gave me an err.
So I tried another way,
def create
#client_group = Client::Group.new(client_group_params)
client_group_params[:created_by] = current_user.id
client_group_params[:users_id] = current_user.id
#client_group.save
respond_with(#client_group)
end
def client_group_params
params.require(:client_group).permit(:group_name)
end
It saved the group_name into the db but it did not save the created_by and the users_id field. Any idea?
I have made the user_id field foreign key.
First, you need to change the assoication declaration as below:
class User < ActiveRecord::Base
belongs_to :client_group,
class_name: 'Client::Group',
foreign_key: :group_id
end
As per the association you have, the User model should have the column called group_id. Add it through migration. I am not seeing the point of adding the user_id to the Group model.
Then change the create action as :
def create
#client_group = current_user.build_client_group(
client_group_params.merge(created_by: current_user.id)
)
#client_group.save
respond_with(#client_group)
end
Related
i have two tables
1)Properties :fields are id, name, propert_type,category_id
2)Admins : fields id, name,mobile,category_id
i want to write an active record to list all properties , where category_id in properties table and category_id in Admins table are equal, according to current_user_id
i am listing this property list by logging as admin.
model relation
class Category < ActiveRecord::Base
has_many :admins,dependent: :destroy
has_many :properties,dependent: :destroy
end
class Admin < ActiveRecord::Base
belongs_to :category
has_many :properties
end
class Property < ActiveRecord::Base
belongs_to :admin
belongs_to :category
end
i wrote active record like this , but i got error,
can anyone please suggest me a solution for this
#properties= Property.where('properties.category_id=?','admins.category_id=?').and('admins.id=?',current_user.specific.id)
With your assosciation,You can use a sub query for getting your result in one line
#properties = Property.where(category_id: Admin.select("category_id").where(id: current_user.id))
As per my understanding current_user is an Admin. So You can search by the category_id of current_user. If I'm right, try this
#properties = Property.where(category_id: current_user.category_id)
I'm tracking the following tables:
Story (id, user_id, content)
Vote (id, user_id, story_id)
Flag (id, user_id, story_id)
etc..
with an activity table:
Activity (id, user_id,action, trackable_id, trackable_type)
The relationship table:
Relationship (id, follower_id, followed_id)
I'm currently getting the activities from users a user is following like this:
def get_activity_from_followers(current_user)
followed_user_ids = "SELECT followed_id FROM relationships
WHERE follower_id = :user_id"
where("user_id IN (#{followed_user_ids})",
user_id: user.id)
end
My question is, how do i get the activities where the the trackable table(e.g. story,vote,flag) belongs to you.
So right now i'm getting things like:
"someone you are following" posted a story
"someone you are following" voted a story
i want to also get things like:
"someone you are not following" voted your story
"someone you are not following" flagged your story
How do I go about this? Thanks.
I suggest you have following class definitions and associations:
# User
class User :trackable
end
# Flag (id, user_id, story_id)
class Flag :trackable
end
# with an activity table:
# Activity (id, user_id,action, trackable_id, trackable_type)
class Activity true
end
# The relationship table:
# Relationship (id, follower_id, following_id)
class Relationship "User"
belongs_to :following, :class_name => "User"
end
Now, Lets find activities of the users to whom you follow:
# List activities of my followings
Activity.where(:user_id => current_user.followings)
Listing my activities
current_user.activities
To solve this, I'd search into Activity using votes and flags id's instead of user id's. Something like this:
def get_votes(current_user)
stories = current_user.stories
votes = Votes.where(story_id: stories.map {|s| s.id})
activity = Activity.where(action: 'vote', trackable_id: votes.map{|v| v.id})
end
I madre some assumptions. First that you can call user.stories, and then that in Activity model 'action' can be vote or flag and that trackable_id relates to Vote and Flag id. If that's not correct, you can get the general idea anyways.
Hope it helps
What about making Activity STI class?
class Story < ActiveRecord::Base
belongs_to :user
end
class Activity < ActiveRecord::Base
belongs_to :story
belongs_to :user
end
class Vote < Activity
def to_partial_path
'users/vote'
end
end
class Flag < Activity
def to_partial_path
'users/flag'
end
end
You can store all user actions in same table and get it from there with:
Activity.where(user_id: uid).all
and you get as return array of all user actions with correct typing for every action, that allow you to implement polymorphic logic for different types of actions (as to partial path in my example, that allows you to write something like:
render Activity.where(user_id: uid).all
I've two models:
class User < ActiveRecord::Base
before_create :add_address
has_one :address
def add_address
self.address_id ||= Address.generate_new.id
end
end
And
class Address < ActiveRecord::Base
belongs_to :user
def self.generate_new
new_address = # some code generating UUID
Address.create!({address: new_address})
end
end
when I create User.new it creates address association, saves it, and I can fetch it with user.address and in mysql Address row has correct user_id, but User in mysql has address_id = nil. What I'm doing wrong? I've tried User.new\user.build_address both ways it creates and saves address but user always has address_id = nil
This is the way it is supposed to be. From the Rails Doc
The distinction is in where you place the foreign key (it goes on the table for the class declaring the belongs_to association)
This means that since your Address model declares the belongs_to, that is where the foreign key should be placed.
What rails does behind the scenes when you search for user.address is does a search for the Address that has a user_id equal to the current user's id.
Something like:
Select * From addresses where user_id = <current_user>.id
Why do you have address_id column in user model? It should be enough for the association to have user_id on the address table.
I am using Ruby on Rails 3 and I successfully use nested models in order to save model\object associations.
In the user model file I have:
class User < ActiveRecord::Base
has_one :account
accepts_nested_attributes_for :account
validates_associated :account
end
After #user.save I would like to retrieve the account id just created and save that value in the user database table. I need that because I will use the account_id as the foreign key for the user class, but I don't know if it is possible. If so, how can I do that?
In my user model I also tryed the following:
before_create :initialize_user
def initialize_user
user_account = Account.create
self.account_id = user_account.id
end
but it doesn't work.
UPDATE
I tryed this
class User < ActiveRecord::Base
belongs_to :account,
:class_name => "Account",
:foreign_key => "users_account_id"
end
class Account < ActiveRecord::Base
has_one :user,
:class_name => "User",
:foreign_key => "users_account_id"
end
and it save the new account. Anyway in the user database table the column users_account_id is null and so the foreign_key value isn't saved automatically.
The Approach is wrong. When you have a "has_one" relationship, they foreign key is in the associated model. So in your case it will in account. And if its accepting nested attributes for account. That should be taken care of by default if you are doing it write.
Take a look http://railscasts.com/episodes/196-nested-model-form-part-1 and the other part as well, to see how nested forms work
def initialize_user
user_account = Account.create
self.account_id = user_account.id
end
should be
def initialize_user
self.account.create
end
When the new Account instance is being created, it will use the information about the current user automatically. Your method would have worked, but you'd have needed to add an extra "save" call.
I have created two models 1) Contact 2) Customer in my Rails application, now I want to join the two tables of these models. Tables are contacts & customers respectively. I am using following code:
1) contact.rb:
class Contact < ActiveRecord::Base
unloadable
has_many :customers
end
2) customer.rb
class Customer < ActiveRecord::Base
belongs_to :contact, :foreign_key => :contact_id`
end
3) customers_controller.rb
def new
#customer = Customer.new
#customer = Customer.find(:all,:include => :contact_id)
end
Here I am trying to access the primary key of contact table into customer table but it repeatedly gives this error "Association named 'contact_id' was not found; perhaps you misspelled it?" Can any one help me on this?
When you use include, you should pass in the association name (in your case "contact") rather than the foreign key.
However, your description doesn't make clear that this is what you want to do, so if you can clarify your question I'll update this answer if it's wrong
If I clearly understand you don't need to pluralize customer in the contact model :
class Contact < ActiveRecord::Base
unloadable
has_many :customers
end
And you don't need to specified the name of the column who contain the foreign key
(sorry for my english)