I want to be able to associate a Post with the User that created the post.
So far I have:
belongs_to :user in my post.rb
and
has_many :post in my user.rb
I know I have to add something to my posts controller but I dont know what. I want each of my posts to have a "Posted by: (user info here)"...
Any help? Thanks in advance.
You can access the user by doing:
#post.user
So you might have:
Posted By: <%= #post.user.username %>
where #post is the variable where the post exists.
You can read up on assocations in rails here, and more specifically in your case here
To answer your question, no you don't need to do anything to your controllers for this functionality to work.
You can reference this association using the user method defined on Post objects by the belongs_to:
<%= post.user.name %>
You can read more in the associations guide.
Related
I am going to do association with user and post model.
I added user_id to post model like this
rails generate migration add_user_id_to_posts
In model
user.rb
has_many :posts
post.rb
belongs_to :user
In post views / it work perfect
<%#posts.each do |post|%>
<%=post.post_name%>
<%=post.user.name.first(20).capitalize, post_path(post.user.id)
<%end%>
In user views /I am getting error
undefined method `post_name' for
#Post::ActiveRecord_Associations_CollectionProxy:0x00007fc9c432bde8
<%#users.each do|user|%>
<%=user.posts.post_name%>
<%=user.name.first(20).capitalize,post_path(user.id)%>
<%end%>
If I want to display like this way what I want to do. Pls need help I am new to rails
I want to add post_id to user model.
The reason you are getting the error is because you're trying to call post_name on a collection of posts that belong to a user. A collection is like an array, so you'll have to iterate through that collection and call post_name on each post.
<% #users.each do |user|%>
<% user.posts.each do |post| %>
<%= post.post_name %>
<% end %>
<%= user.name.first(20).capitalize, post_path(user.id) %>
<% end %>
The reason you're getting a collection of posts is because of your associations. A user has_many posts, which means you are going to get back all the posts that belong to a user. That may mean 0 posts or 10 posts depending on how many times the user has posted.
Because of this, you may want to check if the user has any posts before you iterate through them.
NoMethodError means that method does not exist on that posts. But how and why?
In your first example, post is an object of Post — it must respond_to the method you're calling on it.
To see what methods are available on an object, you can call #methods (which is also available on the class-level):
puts post.methods
That will give you an array of the methods you can call on post.
There is also a method called #class we can call to see what class an object is:
puts user.posts.class
Which will return ActiveRecord::Relation which acts like an array under the hood. Because a User has many Post, we have an array of Post, thus calling name on an array of Post objects will not work.
If you want the first name of the posts that a User has:
user.posts.first.name
But beware, because a user may not have any posts.
I am trying to call value from another model inside the views.
tse.headoffice.head_office_id
Defined the relationship in headoffice.rb as
has_many :tse
and in tse.rb as
belongs_to :headoffice
Now I am getting an error as undefined method
undefined method `head_office_id' for nil:NilClass
<% if tse.headoffice.present? %>
<%= tse.headoffice.head_office_id %>
<% end %>
try() lets you call methods on an object without having to worry about the possibility of that object being nil and thus raising an exception
<%= tse.try(:headoffice).try(:head_office_id) %>
Assuming that the HeadOffice model has an attribute called head_office_id:
<%= tse.headoffice.head_office_id if tse.headoffice %>
If that's not the case:
<%= tse.headoffice_id %>
Something about this doesn't look right. Usually the has_many reference is plural. It's possible your naming scheme is messing with Rails' opinionated magic.
Also why would headoffice have a field called headoffice_id? Wouldn't it just have a field called id? Finally, one nitpick, it should be called head_office not headoffice. And tse is not a good name either. What is tse? Spell it out if you can and form it in a manner that can be singular or plural. Rails works much better if you follow these simple naming guidelines.
https://gist.github.com/iangreenleaf/b206d09c587e8fc6399e
See the simple example below:
post.rb
has_many :comments
comment.rb
belongs_to :post
To access a post's comments you'd type the following:
Post.first.comment.body
Or if you're uncertain about a post having a comment you'd say:
Post.first.try(:comment).try(:body)
I've been looking for a solution for a few days, in a Rails 4.1 app, so here is my question :
In a Rails app, I have my model User and Adress.
class User < ActiveRecord::Base
has_many :adresses
accepts_nested_attributes_for :adresses
class Adress < ActiveRecord::Base
belongs_to :user
accepts_nested_attributes_for :user
In my form, I make a form_tag for User, no problem.
But, how I can display to the final user, in a form, 2 adresses fields?
I use <%= f.fields_for :adress %> to display one, it's ok. But if I display two forms (so the user can enter 2 adresses) they have both the same name and the request post only keep one.
I read the doc at http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for
but, still, I don't get it.
Is there a proper way to do it?
Thanks
I would suggest you to prepare two addresses in new action, add them to the use and then in the form reneder it with foreach.
I found this kind of solution here : http://api.rubyonrails.org/classes/ActionView/Helpers/FormHelper.html#method-i-fields_for
Since you have multiple addresses I think foreach is way to go.
So, to help anyone who is noob in Rails and stuck the same way I was :
In your controller :
#user = User.new
#user.adresses = Adress.new, Adress.new
In your view, form :
<%= form_for #user do |f| %>
<%= f.fields_for :adresses do |a| %>
<%= wp.text_field :name %>
<% end %>
<% end %>
will print the name field for adress two times.
(thanks again to #NickCatib)
How can I get the Username from an ID in Rails 3?
In my view I call <%= blog.user_id %> for the ID, but how do I get the Name there?
The Controller is a scaffold default.
Make sure you define the association in your Blog model.
belongs_to :user
And then in your view your can use <%= blog.user.name %>
Generally you want to avoid long chains of dots like post.user.name. Try:
class Post < ActiveRecord::Base
belongs_to :user
delegate :name, :to => :user, :prefix => true
end
Then in your views you can call
#post.user_name
to get the users name. I thought I would throw this out there since its good habit I am trying to include in my code as well.
You should use <%= blog.user.name %> and have defined
belongs_to :user
in your Blog model. You should work with ..._id on the view-level.
you should learn how to code in Rails, this is a very basic question.
Consider having a look at http://railsforzombies.org
It's a great online tutorial
Try using <%= blog.user.try(:name) %>
Here's my Schema
class Menu < ActiveRecord::Base
belongs_to :menuable, :polymorphic => true
end
class Page < ActiveRecord::Base
has_one :menu, :as => :menuable
end
class Links < ActiveRecord::Base
has_one :menu, :as => :menuable
end
I want to link to a polymorphic class in the Menu view using link_to, e.g.
<%= link_to menu.name, menu.menuable %>
This works, but this retrieves the menuable object from the database, when all I wanted is to generate a link. You can imagine if my menu is large, this will really bog down my application.
When I decared the menuable field as polymorphic, Rails created menuable_type and menuable_id. What can I use to generate a link to the polymorphic page, short of writing a helper function with a giant switch statement (e.g. if I have a large number of menuable 'subclasses'?)
It's been long since the question was asked but I had the same problem recently and the solution was to use polymorphic_url. You need to find the name of the route you need to create a link to, for example "fast_car_path" and make it out of your *_type and *_id from polymorphic table. For example, you have a list of comments and want to make the link to the cars that they belong to. So if *_type = FastCar we have
#comments.each do |comment|
link_to polymorphic_url(comment.commentable_type.tableize.singularize, :id => comment.commentable_id)
which will generate "fast_car_path" without downloading the cars from database.
I am a noob in rails and I dont know how good that advice is, but I hope it will be helpful for somebody.
You could do something like this:
def my_menu_url(menu)
"/#{menu.menuable_type.tableize}/#{menu.menuable_id}"
end
if you use the rails convention for naming the controllers that correspondent to your models.
But don't do it. You work around the routing mechanism of rails and that's simply bad practice.
You should use the :include option in your finders to eager load your menuables:
Menu.all :include => :menuable
In the case this isn't enough you may use some sort of caching.
Another approach could be to use url_for[menu.menuable, menu]. So, the link tag would look like so: <%= link_to menu.name, url_for([menu.menuable, menu]) %>.
you could use polymorphic routes for this
https://api.rubyonrails.org/classes/ActionDispatch/Routing/PolymorphicRoutes.html
<%= link_to menu.name, polymorphic_path(menu.menuable) %>
it will generate html like this
menu.name