Bitwise
Bitwise

Reputation: 8461

Active Record Associations - Rails

Currently I have a Subscriber model that has_many comments and a comment model that belongs to Subscriber. I'm fairly new to rails and I wondering how I connect the two models? So when I create a comment it has the id of the particular Subscriber that made the comment. right now I have a view where a user can input their favorite drink and I want that comment to have one owner. I'll show my code for clarity. Thank You!

COMMENT CONTROLLER:

 class CommentsController < ApplicationController
 def new
  @comment = Comment.new
 end

 def create
  @comment = Comment.create(comments_params)
   if @comment.save
    flash[:notice] = "Subscriber Has Been Successfully Created"
    redirect_to new_subscriber_path(:comments)
   else
    render "new"
   end
  end

  private

  def comments_params
   params.require(:comment).permit(:fav_drink)
  end
end

SUBSCRIBER CONTROLLER:

  class SubscribersController < ApplicationController
  def index
   @subscriber = Subscriber.all
  end

  def new
   @subscriber = Subscriber.new
  end

  def create
    @subscriber = Subscriber.create(subscriber_params)
    if @subscriber.save
     flash[:notice] = "Subscriber Has Been Successfully Created"
     redirect_to new_subscriber_path(:subscriber)
   else
    render "new"
   end
  end

COMMENT MODEL:

 class Comment < ActiveRecord::Base
  belongs_to :subscriber 
 end

SUBSCRIBER MODEL:

 class Subscriber < ActiveRecord::Base
   has_many :comments
 end

The Comment model has a subscriber_id so that is working now I just need to know how to connect the two so that each comment will belong to a particular Subscriber, so that when I user this @comment = @subscriber.comments.first will give the the first comment on that subscriber.

Upvotes: 1

Views: 42

Answers (1)

max pleaner
max pleaner

Reputation: 26788

Basically this line is the one you're going to want to update: @comment = Comment.create(comments_params).

If you wanted to associate the new record with a subscribe, you could include a subscriber_id key in the attributes hash you're passing to Comment.create.

Although comments_param is a method, it returns a hash of attributes which are used to create the new record. In this case it might be { fav_drink: "Tea" }, which needs to have an additional key-val set. I'm not sure how you're planning on getting a subscriber_id, but you'd probably need to have a "current user" system.

This is a separate discussion (how to implement auth in Rails to get the concept of a "current user").

Upvotes: 1

Related Questions