dimanche 12 juin 2016

Joining two models with Rails

I currently have a Subscriber model and a Comment model. The Subscriber has_many comments and the comment belongs_to Subscriber. All I want is for a Subscriber to be able to make a comment in a text field and that comment belongs to that Subscriber through an id. For some reason I can't not figure this out and I'm having a tough time getting help. So, to be very clear I have a subscriber_id on the comment model, how do I attach them together so that I can make this call in the Rails Console - @comment = @subscriber.comments.first and see the first comment that belongs to that particular subscriber? I'll show some code for clarity.

SCHEMA:

         create_table "comments", force: :cascade do |t|
t.string   "description"
t.datetime "created_at",    null: false
t.datetime "updated_at",    null: false
t.string   "fav_drink"
t.string   "visit_time"
t.integer  "subscriber_id"
end

create_table "subscribers", force: :cascade do |t|
t.string   "first_name"
t.string   "last_name"
t.string   "email"
t.string   "phone_number"
t.string   "birthdate"
t.string   "street_1"
t.string   "street_2"
t.string   "city"
t.string   "zip"
t.string   "state"
t.datetime "created_at",   null: false
t.datetime "updated_at",   null: false
t.integer  "visit"
end

CONTROLLERS:

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

def create
  @comment = Comment.create(comments_params)
  if @comment.save
    flash[:notice] = "Thank you!"
    redirect_to subscribers_search_path(:comments)
  else
    render "new"
  end
end

private

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



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

And the Models are as described in the intro. Thank You!

Aucun commentaire:

Enregistrer un commentaire