본문 바로가기

개발/Ruby

[Code School] Rails for Zombie

===lv1. CRUD


db의 table name이 tweets이면

Tweet으로 접근 가능


create할때

t = Tweet.new

t.status = "blah"

t.save


t = Twee.create(status: "blah")


t = Tweet.new(status: "haha", name: "allie")

t.save

key에 따움표 안 들어가는거 유념하기


R

Tweet.find(3)


Tweet.find(3,4,5)

Twwet.first

Tweet.last


U

t = Tweet.find(3)

t.update(~~)


t.attributes(~~)

t.save


D

t = Tweet.find(3)

t.destroy




Tweet.order('name')




===lv2.model

app/models/tweet.rb


#ActiveRecord::Base는 클래스를 디비로 매핑해줌

class Tweet < ActiveRecord::Base

belongs_to :zombie


validates_presence_of :status

validates_numericality_of :fingers

validates_uniqueness_of :toothmarks

등등..


validates :status,

presence: true,

length: {minimum:3}

end



==== lv4. controllers


==== lv5. routes

action                         code                                 url

list all twetts            tweets_path                     /tweets

new tweet form       new_tweet_path              /tweets/new

show a tweet           tweet                               /tweets/1

edit a tweet             edit_tweet_path(tweet)    /tweets/1/edit

delete a tweet        tweet, :method => :delete   /tweets/1



http://localhost:3000/new_tweet라고 치면 http://localhost:3000/tweets/new 가 render

아래 tweets#new에서 tweets은 컨트롤러 이름(TweetsController)

new는 action이름임..

ZombieTwitter::Application.routes.draw do

resources :tweets

get '/new_tweet' => 'tweets#new'

end


컨트롤러 생김새는

class TweetsController

def new

..

end

end




TwitterForZombies::Application.routes.draw do

  get '/undead', to: redirect('/zombies')

end




root to: "tweets#index"

<%= link_to "All Tweets", root_path %>



get ':name' => 'tweets#index', as: 'zombie_tweets'

<%= link_to "Gregg", zombie_tweets_path('greggpollac') %>

(index에 params[:name] 체크하는게 있어야함

def index

if params[:name]

@zombie = Zombie.where(name: params[:name]).first

@tweets = @zombie.tweets

else

@tweets = Tweet.all

end

end


'개발 > Ruby' 카테고리의 다른 글

코드라이언 - 새로운 프로젝트 만들기  (0) 2016.08.19
rails tutorial  (0) 2016.04.14
[Code School] Rails for Zombies 2  (0) 2016.04.12