반응형
250x250
Notice
Recent Posts
Recent Comments
Link
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
Archives
Today
Total
관리 메뉴

가끔 보자, 하늘.

ruby on rails 시작해보기 - 3 본문

개발 이야기/개발 및 서비스

ruby on rails 시작해보기 - 3

가온아 2014. 6. 7. 08:44

"http://guides.rubyonrails.org/getting_started.html " 5 Getting Up andRunning 이하 내용.


5.x 부터는 튜토리얼을 그대로 따라가면서 진행 중 ^^a


------------------------------------------------------------------------------------

5.5 Running a Migration


지금까지 본 것처럼, Rails는 Model을 db/migrate 디렉토리 안에 database migration 파일을 생성한다.  Migrations는 database 테이블들의 생성과 수정이 간단히 만들어지게 디자인된 Ruby 클래스다.  Rails 마이그레이션을 실행하는 rake 명령어를 사용한다. 그리고 이건 당신의 DB에 적용된 마이그레이션 한 결과를 되돌리는것이 가능하다. 마이그레이션 파일이름에는 날짜가 포함되어 있으며, 이를 통해 undo가 가능하다.


db/migrate/20140521122056_create_articles.rb 파일(파일명의 날짜는 당신이 생성한 날짜로 생성된다.)을 보면, 아래와 같은 내용을 볼 수 있다.


class CreateArticles < ActiveRecord::Migration
  def change
    create_table :articles do |t|
      t.string :title
      t.text :text
 
      t.timestamps
    end
  end
end


rake 명령을 이용해서 migration을 실행하자.


$ rake db:migrate


Rails는 Articles 테이블을 생성해 줄거다.


기본적으로 우리는 개발환경에서 작업을 하기 때문에, 이 명령어는 config/database.yml의 개발섹션에 정의된 정보를 반영하여 생성한다. 만약 다른 환경에서 migration을 실행하길 원한다면, rake 명령을 실행할 때, 인자값을 확실히 전달해야 한다. : rake db:migrate RAILS_ENV=production


5.6 Saving data in the controller

ArticlesController으로 돌아가서, database에 정보를 저장하는 새로운 Article Model을 사용하기 위해 create action을 변경하는 작업이 필요하다. app/controllers/articles_controller.rb를 열고, 아래와 같은 내용으로 수정하자.


def create
  @article = Article.new(params[:article])
 
  @article.save
  redirect_to @article
end


Rails Model은 database 컬럼에 자동으로 매핑된 속성에 초기에 바로 적용되게 할 수 있다. 첫번째 라인이 바로 그것이다. 다음으로, @article.save는 db에 모델을 저장한다. 마지막으로, 유저에게 결과를 보여준다.


나중에 다시 볼 수 있는데, @article.save 는 정상적으로 저장되었는지, 혹은 실패했는지를 boolean값으로 돌려준다.


http://localhost:3000/articles/new 로 가보면 아래와 같은 에러를 보게된다.


ActiveModel::ForbiddenAttributesError in ArticlesController#create

ActiveModel::ForbiddenAttributesError

Extracted source (around line #6):

4 5 6 7 8 9

def create
@article = Article.new(params[:article])
@article.save
redirect_to @article


Rails는 안전한 어플을 만들 수 있도록 도와주는 여러가지 보안 기능을 제공한다. 우리는 title,text 파라미터만 허락하길 원하니 article_params를 아래와 같이 더해보자.


def create
  @article = Article.new(article_params)
 
  @article.save
  redirect_to @article
end
 
private
  def article_params
    params.require(:article).permit(:title, :text)
  end


이 action에서 사용된 permit은 title과 text 두개만 수락하도록 한다.


"def article_params"는 private이다.  이는 속성값으로 위장되어 모델에 전달되는 것을 방지할 수 있다. 더 많은 정보를 위해서는  the blog article about Strong Parameters 를 참고하라.


5.7 Showing Articles


이제 다시 새로운 글을 쓰고 submit 버턴을 눌러보자. Rails는 show action을 찾을 수 없다고 투덜거릴거다. 더 진행하기 전에 show action을 추가해보자.


rake routes 의 결과에서 본 것처럼, show action을 위한 그 route는 아래와 같다.


article GET    /articles/:id(.:format)      articles#show


app/controllers/articles_controller.rb에 show action을 추가해보자.


def show
  @article = Article.find(params[:id])
end


두가지를 주목해야 한다. 우리는 우리가 원하는 article을 찾기 위해 요청 정보에 포함된 :id 인자값을 가져오는 params[:id]를 Article.find에 전달하여 찾는다. 또한, article object를 참조하기 위해 @를 앞에 붙인 임시 변수를 사용하는데, Rails는 이 임시 변수들을 view에도 전달하기 때문에 이렇게 사용할 수 있다.


이제, 아래와 같이 app/views/articles/show.html 파일을 새로 만들자.


<p>
  <strong>Title:</strong>
  <%= @article.title %>
</p>
 
<p>
  <strong>Text:</strong>
  <%= @article.text %>
</p>


마침내 새로운 아티클을 생성할 수 있게 되었다. 이제  http://localhost:3000/articles/new 로 접속해서 다시 시도를 해보자. 


5.8 Listing all articles


우린 아직 우리의 모든 articles에 대한 리스트를 볼 수 있는 방법이 필요하다. 이제 이걸 해보자. rake route에서 아래 내용을 볼 수 있었다.


articles GET    /articles(.:format)          articles#index


app/controllers/articles_controller.rb 파일의 ArticlesController 안에 index action을 추가해보자.


def index
  @articles = Article.all
end


그리고 마지막으로, app/views/articles/index.html.erb에 이 액션에 view를 추가하자.


<h1>Listing articles</h1>
 
<table>
  <tr>
    <th>Title</th>
    <th>Text</th>
  </tr>
 
  <% @articles.each do |article| %>
    <tr>
      <td><%= article.title %></td>
      <td><%= article.text %></td>
    </tr>
  <% end %>
</table>


이제 http://localhost:3000/articles 로 가면, 지금까지 등록한 모든 글들의 리스트를 볼 수 있다.


5.9 Adding links


이제 글을 생성하고, 글을 보고, 리스트를 볼 수 있습니다. 이제, 페이지를 넘나드는 몇몇 링크를 추가해보자.


app/views/welcome/index.html/erb를 열고, 아래와 같이 수정하자.


<h1>Hello, Rails!</h1>
<%= link_to 'My Blog', controller: 'articles' %>

link_to method는 Rails의 built-in view helpers 중 하나이다. 이걸 사용하면 텍스트 기반의 하이퍼링크를 만들 수 있는데, 여기서는 article로 연결해주자.


<table> 태크 아래에, add/views/articles/index.html.erb "새글쓰기"링크를 추가해보자. 


<%= link_to 'New article', new_article_path %>


app/views/articles/new.html/erb에 index action으로 돌아가는 링크를 넣어보자.


<%= form_for :article, url: articles_path do |f| %>
  ...
<% end %>
 
<%= link_to 'Back', articles_path %>


마지막으로, app/views/articles/show.html.erb에도 index action으로 돌아가는 링크를 추가하자. 그렇게하면 글을 보던 사람이 전체 리스트 보기로 돌아갈 수 있다.

<p>
  <strong>Title:</strong>
  <%= @article.title %>
</p>
 
<p>
  <strong>Text:</strong>
  <%= @article.text %>
</p>
 
<%= link_to 'Back', articles_path %>


만약 같은 컨트롤 안의 액션으로 링크할 때는, :controller 옵션을 명시할 필요는 없다. 레일즈는 기본적으로 현재의 컨트롤을 사용하기 때문이다.


개발모드에서는 매 요청마다 어플리케이션을 리로드하기 때문에, 서버를 재시작할 필요는 없다. 



5.10 Adding Some Validation


app/models/article.rb  모델 파일은 간단합니다. 


class Article < ActiveRecord::Base
end


아직 충분한 내용은 아니다. 하지만, Article class가 ActiveRecord::Base를 상속받은 것은 중요하다. Active Record는 기본적인 database CRUD(Create, Read, Update, Destroy) 기능들을 쉽게 처리할 수 있도록 해준다. 게다가, 정교한 검색을 제공하며, 또다른 모델을 동시 처리할 수 있다. 


Rails는 당신이 모델에 보낸 정보를 처리할 수 있는 방법들을 제공한다.  app/models/article.rb 파일을 열고 아래와 같이 수정하자.


class Article < ActiveRecord::Base
  validates :title, presence: true,
                    length: { minimum: 5 }
end


위 내용이 적용되면, 모든 기사의 제목을 최소 5자로 설정하게 설정하도록 할 수 있다. Rails는 여러가지에 대한 검증을 할 수 있다. 검증에 대해서는  Active Record Validations를 참고하라.


여기서는 @article.save를 호출할 때, 글에 어떤 문제가 있을 경우 false를 리턴시켜 볼 것이다. app/conrollers/articles_controller.rb를 다시 열어보면,  @article.save의 리턴값을 확인하지 않는다는 것을 알 수 있다. 그래서 @article.save가 실패할 경우, 유저에게 실패를 알리고, 돌아갈 수 있게 하는게 필요하다. 그렇게 하려면, app/controllers/articles_controller.rb 파일 안의 new와 create를 아래와 같이 바꿔보자.

def new
  @article = Article.new
end
 
def create
  @article = Article.new(article_params)
 
  if @article.save
    redirect_to @article
  else
    render 'new'
  end
end
 
private
  def article_params
    params.require(:article).permit(:title, :text)
  end










반응형