Rectangle 27 10

def create
  @post = Post.find(params[:post_id])
  @comment = @post.comments.create(comment_params)
  @comment.user_id = current_user.id #or whatever is you session name
  if @comment.save
    redirect_to @post
  else
    flash.now[:danger] = "error"
  end
end

And also you should remove user_id from comment_params as strong parameters . Hope this will help you .

Add Comment to User and Post models (Ruby on Rails) - Stack Overflow

ruby-on-rails ruby ruby-on-rails-4
Rectangle 27 7

To give you a definition of what's happening here, you have to remember whenever you create a record, you are basically populating a database. Your associations are defined with foreign_keys

When you ask how to "add comments to User and Post model" - the bottom line is you don't; you add a comment to the Comment model, and can associate it with a User and Post:

#app/models/comment.rb
Class Comment < ActiveRecord::Base
    belongs_to :user
    belongs_to :post
end

This prompts Rails to look for user_id and post_id in the Comment model by default.

This means if you wanted to create a comment directly, you can associate it to either of these associations by simply populating the foreign_keys as you wish (or use Rails objects to populate them)

So when you want to save a comment, you can do this:

#app/controllers/comments_controller.rb
Class CommentsController < ApplicationController
   def create
       @comment = Comment.new(comment_params)
   end

   private

   def comment_params
        params.require(:comment).permit(:user_id, :post_id, :etc)
   end
end

Conversely, you can handle it by using standard Rails objects (as the accepted answer has specified)

Add Comment to User and Post models (Ruby on Rails) - Stack Overflow

ruby-on-rails ruby ruby-on-rails-4
Rectangle 27 0

To give you a definition of what's happening here, you have to remember whenever you create a record, you are basically populating a database. Your associations are defined with foreign_keys

When you ask how to "add comments to User and Post model" - the bottom line is you don't; you add a comment to the Comment model, and can associate it with a User and Post:

#app/models/comment.rb
Class Comment < ActiveRecord::Base
    belongs_to :user
    belongs_to :post
end

This prompts Rails to look for user_id and post_id in the Comment model by default.

This means if you wanted to create a comment directly, you can associate it to either of these associations by simply populating the foreign_keys as you wish (or use Rails objects to populate them)

So when you want to save a comment, you can do this:

#app/controllers/comments_controller.rb
Class CommentsController < ApplicationController
   def create
       @comment = Comment.new(comment_params)
   end

   private

   def comment_params
        params.require(:comment).permit(:user_id, :post_id, :etc)
   end
end

Conversely, you can handle it by using standard Rails objects (as the accepted answer has specified)

Add Comment to User and Post models (Ruby on Rails) - Stack Overflow

ruby-on-rails ruby ruby-on-rails-4
Rectangle 27 0

rails_admin: it allows you to manage your blog by going to yourapp.com/admin. It uses devise to create an Admin user (you can specify a diferent model name than user to not to mix it with the users from omniauth or from your other app) and if you have the right models and associations between them you can from there create your posts, assign them tags or categories and also delete comments etc.. its all done in an easy way. For the Text Area that you use to introduce the content of your posts you can associate it with the ckeditor just by adding to the rails_admin initializer something like:

config.model Post do
  edit do
    field :body, :text do
      ckeditor true
    end
  end
end

content management system - Rails 3 CMS + blog wanted to fit existing ...

ruby-on-rails-3 content-management-system
Rectangle 27 0

Class CommentsController < ApplicationController
  before_action :set_user
  before_action :set_post

  def create
    @comment = @post.comments.create(comment_params)

    if @comment.save
      redirect_to @post
    else
      flash.now[:danger] = "error"
    end
  end

  private

    set_post
      @post = User.posts.find(params[:post_id])
    end

   set_user
      @user = User.find(params[:user_id])
   end

   comment_params
     params[:comment].permit()
   end

Code only and "try this" answers are usually discouraged, please add some explanation.

User has_many posts and Post has-many comments So first of all you don't really need direct association with comments. You can use User has_many :comments, through: :posts. So @post.comments.create(comment_params) will work.

Add Comment to User and Post models (Ruby on Rails) - Stack Overflow

ruby-on-rails ruby ruby-on-rails-4
Rectangle 27 0

You will only need to add a Tagging model, and use a polymorphic association to handle Likes. So, you need a User, Post, Comment, Like, Tag, and Tagging

You will not need a controller for Tags or Taggings or Likes

If you want users to be able to create posts and comments as well as like both posts and comments, then here is one way to configure your models:

class User < ActiveRecord::Base
    has_many :posts
    has_many :comments
    has_many :likes, as: :likeable, dependent: :destroy
end
class Post < ActiveRecord::Base
    belongs_to :user
    has_many   :comments
    has_many   :likes, as: :likeable, dependent: :destroy

    has_many :taggings
    has_many :tags, through: :taggings

    def self.tagged_with(name)
      Tag.find_by_name!(name).posts
    end

    def self.tag_counts
      Tag.select("tags.*, count(taggings.tag_id) as count").
        joins(:taggings).group("taggings.tag_id")
    end

    def tag_list
      tags.map(&:name).join(", ")
    end

    def tag_list=(names)
      self.tags = names.split(",").map do |n|
        Tag.where(name: n.strip).first_or_create!
      end
    end

end
class Comment < ActiveRecord::Base
    belongs_to :user
    belongs_to :post
end
class Like < ActiveRecord::Base
    belongs_to :likeable, polymorphic: true
end
rails g model tag name
class Tag < ActiveRecord::Base
  has_many :taggings
  has_many :posts, through: :taggings
end
rails g model tagging tag:belongs_to post:belongs_to
class Tagging < ActiveRecord::Base
  belongs_to :tag
  belongs_to :post
end

The Post model assumes your tag uses the attribute :name

get 'tags/:tag', to: 'posts#index', as: :tag

And change your index action in your Posts controller to this:

def index
    if params[:tag]
        @posts = Post.tagged_with(params[:tag])
    else
        @posts = Post.all
    end
end
<%= raw @post.tags.map(&:name).map { |t| link_to t, tag_path(t) }.join(', ') %>

I have a problem with this snippet: Tag.find_by_name!(name).posts. I get this error: undefined method posts' for #<Tag:0x007fdc5a1c7260>`

Rails Model: How to do the relation - Stack Overflow

ruby-on-rails
Rectangle 27 0

def create
  @post = Post.find(params[:post_id])
  @comment = @post.comments.create(comment_params)
  @comment.user_id = current_user.id #or whatever is you session name
  if @comment.save
    redirect_to @post
  else
    flash.now[:danger] = "error"
  end
end

And also you should remove user_id from comment_params as strong parameters . Hope this will help you .

Add Comment to User and Post models (Ruby on Rails) - Stack Overflow

ruby-on-rails ruby ruby-on-rails-4
Rectangle 27 0

I prefer embedding instead of linking for such this cases. Your scenario is very suitable for embedding. I would create 2 models. One of them is Account, another is User. The reason of defining User model separately is defining your user models behavior. Let say, you are adding a user to specified account with an registration form. When you post form, you can directly cast form body post values to User model and embed it to Account model. I have created models like;

Account = new Schema({
    users:{
        type:[User],
        required:true
    },
    modified:{
        type:String,
        required:false
    }
});

User = new Schema({
    name:{
        type:String,
        required:true
    },
    email:{
        type:String,
        required:true
    },
    password:{
        type:String,
        required:true
    }
});

You can also have a look at gist here for example definition.

This does not work well if a user is allowed to belong to multiple accounts so I'm sticking with linking for now.

You can embed user into several accounts

yes but if any info about the user changes, every account needs to be updated.

MongoDB/Mongoose Schema for Accounts with Multiple Users - Stack Overf...

mongodb mongoose database-schema
Rectangle 27 0

artist=Artist who is logged in
artist.artist_micro_posts.build(attributes)
artist.save
micro_posts= Micropost Id
 micro_post.artist_micropost_comments.build(:artist_id=logged in person)
micro_post.save

I don't see the difference between this and what I already have.

Add Comment to User and Post models Rails 4 - Stack Overflow

ruby-on-rails ruby-on-rails-4 activerecord
Rectangle 27 0

Validation should be put at least on the view model because this is what you receive as user input. As far as validation on the model is concerned you could add it as well but as long as you are passing a view model to your POST action (which is exactly what you should do) the validation on the model will be ignored. Of course that's not a problem here because a model is something that might be reused on other applications as well which don't use view models and this way your model is guaranteed to be valid. As far as ASP.NET MVC is concerned this step is not necessary.

asp.net mvc - Where to put validation annotations ViewModel or Domain ...

asp.net-mvc automapper
Rectangle 27 0

it looks like you didn't made the relation between those models add to addresses column called user_id and add to user model:

has_many :addresses

and into addresses:

belongs_to :users

then in your view you can build this form using nested attributes see this post:

another option that you can do is to show that addresses form after the user already signed in then when he update the form find the user_id with current_user and build the record using this id but using strong params in Rails 4 is recommended to solve your issue.

ruby on rails - Trying to add a foreign relationship to my users model...

ruby-on-rails devise
Rectangle 27 0

For adding a feature to enable users to favorite other users post you will need to create an association with the User and Post models that you might already have created

class User < ActiveRecord::Base
  has_many :posts
  has_many :favorites, :dependent => :destroy
  has_many :favorite_posts, :through => :favorites, :source => :post
end

class Post < ActiveRecord::Base
  belongs_to :user
  has_many   :favorites, :dependent => :destroy
  has_many   :favorited, :through => :favorites, :source => :user
end

class Favorite < ActiveRecord::Base
  belongs_to :user
  belongs_to :post
end

You can use these models to add the necessary features and create posts and favorites using this associations.

This code will now give the favorite posts of user444 if you do myname.favorite_posts

i have do what you tell me and i have create a fvorite controller def create current_user.favorites.create(params[:post_id]) end this is routes get "favorites/create" and i have add a button to posts <%= button_to 'Add to Favorites', favorites_create_path %>

and this is my view <%= post_title.current_user.favorites%> but when click to the add button and go to favorite path i get this error undefined local variable or method `post_title'

Is post_title defined in your Post model ?

User Favorites System in Rails - Stack Overflow

ruby-on-rails ruby-on-rails-4
Rectangle 27 0

I prefer embedding instead of linking for such this cases. Your scenario is very suitable for embedding. I would create 2 models. One of them is Account, another is User. The reason of defining User model separately is defining your user models behavior. Let say, you are adding a user to specified account with an registration form. When you post form, you can directly cast form body post values to User model and embed it to Account model. I have created models like;

Account = new Schema({
    users:{
        type:[User],
        required:true
    },
    modified:{
        type:String,
        required:false
    }
});

User = new Schema({
    name:{
        type:String,
        required:true
    },
    email:{
        type:String,
        required:true
    },
    password:{
        type:String,
        required:true
    }
});

You can also have a look at gist here for example definition.

This does not work well if a user is allowed to belong to multiple accounts so I'm sticking with linking for now.

You can embed user into several accounts

yes but if any info about the user changes, every account needs to be updated.

MongoDB/Mongoose Schema for Accounts with Multiple Users - Stack Overf...

mongodb mongoose database-schema
Rectangle 27 0

This seems like a job for STI (single table inheritance)! Add a type column to your User model, and have the Employer and Candidate models inherit from User. There are a lot of STI with rails references out on the internet, but here's one specific blog post.

Yeah this is what I have been looking at. If I inherit from the user I only get the fields available in user.rb but not the fields available in employer.rb when I do employer.new

Right, you would add the employer-specific columns to the employer model.

I have different fields in the employer.rb but it returns only the user.rb columns

STI will inherit from the parent in this case user.rb but I need the user depending on the role to be able to update the columns in employer.rb

I got fed up just push all the fields into user and went with STI

ruby on rails - Devise + CanCan + Different Models (roles) - Stack Ove...

ruby-on-rails devise cancan
Rectangle 27 0

You need 2 models: User and Post. There is a relation between them: User HAS MANY posts, post BELONGS TO user. To create this relation in a database you should add user_id column to posts table. To do this simply run the following command:

rails generate migration AddUserIdToPosts user_id: integer

Don't forget to run rake db:migrate after that

To create association between models add to the User model:

has_many :posts, dependent: :destroy
belongs_to :user

Now you can use 'user' method on post and 'posts' method on user. For example in show action of users controller:

@user = User.find(params[:id])
@posts = @user.posts

ruby on rails - How can I get all posts from a specific user - Stack O...

ruby-on-rails blogs
Rectangle 27 0

Artist
Micropost
Comment
class Artist < ActiveRecord::Base
  has_many :microposts, dependent: :destroy
  has_many :comments, through: :microposts, dependent: :destroy
end

class Micropost < ActiveRecord::Base
  belongs_to :artist
  has_many :comments, dependent: :destroy
end

class Comment < ActiveRecord::Base
  # I renamed artist to commenter to make it clear that is not the same artist as the one that created the micropost,
  # this implies that instead of author_id you will have commented_id in comments table

  belongs_to :commenter, :class_name => Artist
  belongs_to :micropost
end


### views/artists/show.html.erb ###

<% @artist.microposts.each do |micropost| %>
  ...
  <%= micropost.content %>
  ...


  <% micropost.comments.each do |comment| %>
    # here you display comments for each micropost
    <%= comment.content %>

    # pay attention at the way I builded the comment
    <%= form_for(micropost.comments.build) do |f| %>
      <%= f.hidden_field :micropost_id %> # this will make the link to your micropost
      <%= f.text_area :content %>
      <%= f.submit "post comment" %>
    <% end %>
  <% end %>
<% end %>

In your comments_controller you must assign current logged in artist (the commenter) to your comment.

class CommentsController < ApplicationController
  def create
    @comment = Comment.new(comment_params)
    @comment.commenter = current_artist

    if @comment.save
      ...
    end 
  end

  private

  def comment_params
    params.require(:comment).permit(:micropost_id, :content)
  end
end

To avoid N+1 when you load artists, microposts and commenters do something like this:

class ArtistsController < ApplicationController
  def show
    @artist = Artist.includes(:microposts, :comments => :commenter).find(params[:id])
  end
end

Add Comment to User and Post models Rails 4 - Stack Overflow

ruby-on-rails ruby-on-rails-4 activerecord