I'm developing a blog site for practice. My problem is I can't call data from one object to another related object.
Here are my model associations:
1 class Post < ActiveRecord::Base
2 belongs_to :user
3 end
1 class User < ActiveRecord::Base
2 has_many :posts
3 end
In the console:
user = User.find(1)
user.posts // Everything works! It shows me a list of posts related to the user.
user.post(1) //This doesn't work! Is it wrong?
I've been looking over active record query interface guide at rubyonrails.org and still can't find anything in reference to this. Maybe I missed something?
Thanks
Do it this way:
user.posts[0] #=> returns the user's first post
Related
I am new to ruby on rails. As a part of my learning I created a sample application. In the sample app i have 2 models : tweet, user
I defined the relationship in my model, which defines the following : A Tweet has a User , A User has many Tweets. Here is how my code looks like :
class User < ActiveRecord::Base
attr_accessible :user_email, :user_name, :user_password
has_many :tweet
end
class Tweet < ActiveRecord::Base
attr_accessible :post_title
belongs_to :user
end
Now I want to get this updated in my database. I wanted to check if there is anyway this can be updated automatically e.g. running rake db:migrate or something else. Or if I have do it manually ?
Thanks for all your help.
First of all add a column user_id in your tweet table, which will store the user's id, This user_id will be the key to identify the tweets of an user. And then change the line
has_many :tweet
to
has_many :tweets
and it will work.
Thanks
Let's assume I have two models.
class User < ActiveRecord::Base
has_one :blog
end
class Blog < ActiveRecord::Base
belongs_to :user
validates_presence_of :user
validates_uniqueness_of :user_id
end
Let's assume I have one user with a blog. For some reason, let's pretend I call create_blog for the same user (I know it should not be an option since the user already has a blog). If this blog doesn't pass the validations, and it won't, not only isn't saved, but it deletes the previous blog the user has.
Why is this happening? Why the initial blog gets deleted? Is this behavior expected or is there something I missing?
By calling create_blog you're telling Rails to discard the previous blog. There isn't a way around this (that I am aware of) that doesn't involve doing something like this:
blog = Blog.new(params[:blog])
if blog.valid?
user.blog = blog
user.save
end
I have 2 models in my Rails 3 app
User:
class User < ActiveRecord::Base
acts_as_followable
acts_as_follower
has_many :posts
end
Post:
class Post < ActiveRecord::Base
belongs_to :user
end
So, I can fetch users that I follow: User.find(1).following_users
But how to fetch posts of followed users? Something like User.find(1).following_users.posts
User.find(1).following_users just returns and arel reference, see here:
https://github.com/tcocca/acts_as_follower/blob/master/lib/acts_as_follower/follower.rb#L59
So,
User.find(1).following_users.includes(:posts)
should include the posts for the users in the query, but this will return an array of users. The following should work, loop through the users that are returned and collect their posts into an array
posts = User.find(1).following_users.includes(:posts).collect{|u| u.posts}.flatten
User.following_users.collect{|u| u.posts}
This should work
I print in my view a number that tell me, how many people read my article. It looks something like a:
<%=article.hits.count%>
As is possible to see, I created a simple association.
Now I am trying to get the information, if the user who is log in on my page, so if he is already had read this article. In my table that contains hits is column user_id.
But I can't still find the way, how to get...
I tried something like:
<% if session[:login_user_id].hits.user_id == session[:login_user_id]%>
Have you read it already.
<% end %>
But the example above doesn't work me... Could anyone help me please, how to do?
EDIT: The models:
class Article < ActiveRecord::Base
has_many :hits
end
class Hits < ActiveRecord::Base
belongs_to :article, :class_name => "DataHit", :foreign_key => "article_id"
has_many :users
end
class User < ActiveRecord::Base
belongs_to :hit
end
Thanks in advance
Let's first talk about the model you like to receive. For me, it sounds like:
Every article can be visited / read by many users.
Every user can read / visit many articles.
This is a classical n:m-association which is normally implemented by a has-many-through association.
If this is the intention, it should be implemented like:
class Article < ActiveRecord::Base
has_many :hits
has_many :users, :through => :hits
end
class Hits < ActiveRecord::Base
belongs_to :article, :class_name => "DataHit", :foreign_key => "article_id"
belongs_to :user
end
class User < ActiveRecord::Base
has_many :hits
has_many :articles, :through => :hits
end
Of course, you have to add migrations that ensure that the final DB model is like that:
Hit has article_id and user_id to ensure that users may find the articles they have read
If you have that model implemented, it should be more easy. Then you have operations available like: #article.users.contains(User.find(user_id)). Have a look at the tutorial at Ruby on Rails Guides which explain what the has-many-through relation is and which advantages they have.
It would be helpful if you try the things first in the console of Rails. To do that, start with:
Start the rails console in the root directory of your application: rails c
Enter there e.g.: art = Article.find(1) to get the article with the id.
Try which methods are available: art.methods.sort to see all methods that could be used. If there is no method users, you have did something wrong with the assocication.
Try the call: us = art.users and look at the result. It should be a rails specific object, an object that behaves like a collection and understands how to add and remove users to that collection (with the whole life cycle of rails). The error your currently have could mean different things:
Your database model does not match your associations defined in Rails (I suspect that).
Some minor tweak (misspelling somewhere) which hinders Rails.
I hope this gives you some clues what to do next, I don't think that we can fix the problem here once and for all times.
assume we the following setup:
class Post < ActiveRecord::Base
belongs_to :user
end
class User < ActiveRecord::Base
has_many :posts
end
assume further the user has a boolean attribute 'admin', which indicates if he is a global admin or not.
I want to write a method (or a scope?) for the User class, called 'visible_posts'. If the user is no admin, it should return just its own posts. If he IS admin the method should return all posts in the system.
My first attempt was something like this:
class User < ActiveRecord::Base
[...]
def visible_posts
if admin?
Post.all
else
posts
end
end
end
Problem here is that Post.all returns an Array, but I would rather like to have an ActiveRecord::Relation like I get from posts to work with it later on.
Is it somehow possible to get an ActiveRecord::Relation that represents ALL posts ?
You can do Post.scoped i guess in Rails
And later on this you can call .all to fetch the results