에 저장되는 곳 책 RELATED_TO : 제목 및 주제 has_many : 책내가 내가 내가 모델 예약 및 제목 관련 한 점 에 붙어 레일에 초보자 오전 DB
이제 책 인스턴스를 저장하는 동안 내가 제목 필드를 저장하기 위해 무엇을 할 수 있는지
책 모델 파일 : book.rb
class Book < ActiveRecord::Base
attr_accessible :title, :price,:description , :created_at ,:subject
belongs_to :subject
validates_presence_of :title
validates_numericality_of :price, :message=>"Error Message"
end
대상 모델 파일 : subject.rb
class Subject < ActiveRecord::Base
attr_accessible :name
has_many :books
end
내 마이그레이션 파일이 책 마이그레이션
class Books < ActiveRecord::Migration
def self.up
create_table :books do |t|
t.column :title, :string, :limit => 32, :null => false
t.column :price, :float
t.column :subject_id, :integer
t.column :description, :text
t.column :created_at, :string
end
Book.create :title =>"book1",:price =>500 , :description=>"book 1 created" , :created_at=>"12/12/12"
Book.create :title =>"book2",:price =>111 , :description=>"book 2 created" , :created_at=>"12/12/12"
Book.create :title =>"book3",:price =>222 , :description=>"book 3 created" , :created_at=>"12/12/12"
Book.create :title =>"book4",:price =>333 , :description=>"book 4 created" , :created_at=>"12/12/12"
Book.create :title =>"book5",:price =>444 , :description=>"book 5 created" , :created_at=>"12/12/12"
end
def self.down
drop_table :books
end
end
주제 마이그레이션
class Subjects < ActiveRecord::Migration
def self.up
create_table :subjects do |t|
t.column :name, :string
end
Subject.create :name => "Physics"
Subject.create :name => "Mathematics"
Subject.create :name => "Chemistry"
Subject.create :name => "Psychology"
Subject.create :name => "Geography"
end
def self.down
drop_table :subjects
end
end
내 newBook의 html.erb
<html>
<head>
<title> new Book </title>
</head>
<body>
<h1><%= @hello_message %></h1>
<h1>Add new book</h1>
<%= form_tag :action => 'create' %>
<p>
<label for="book_title">Title</label>:
<%= text_field 'book', 'title' %>
</p>
<p>
<label for="book_price">Price</label>:
<%= text_field 'book', 'price' %>
</p>
<p>
<label for="book_subject">Subject</label>:
<%= collection_select(:book,:subject_id,@subjects,:id,:name) %>
</p>
<p>
<label for="book_description">Description</label>
<br/>
<%= text_area 'book', 'description' %>
</p>
<%= submit_tag "Create" %>
<%= form_tag %>
<%= link_to 'Back', {:action => 'list'} %>
</body>
</html>
난 내 생성 작용에 의해 저장하려고하면
그것이 대량 할당 보호 할 수 없습니다 속성은 말한다 : 도서 모델에서
완벽한, 내가 이런 짓을하지만, 다른 실수를하지만, 당신의 대답 후 –
BTW 그것을 가지고, 당신은 왜 당신이 어떻게 설정합니까 손으로 created_at 값? –
내가 자동으로 생성하는 방법을 모르겠다. –