Skip to content

Instantly share code, notes, and snippets.

@pierangelo1982
Forked from Mikke/01_step.sh
Last active August 29, 2015 14:13
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pierangelo1982/25a3dd285aed32c976b0 to your computer and use it in GitHub Desktop.
Save pierangelo1982/25a3dd285aed32c976b0 to your computer and use it in GitHub Desktop.
rails g scaffold Book title:string description:text
rails g scaffold Pubhouse title:string address:text
rails g model BookPubhouse book_id:integer pubhouse_id:integer
rake db:migrate
# 'app/models/book.rb'
class Book < ActiveRecord::Base
has_many :book_pubhouses, :dependent => :destroy # уничтожать вместе с основным экземпляром
has_many :pubhouses, :through => :book_pubhouses # through указывает Rails приложению зависимость двух моделей через третью, теперь мы можем использовать Book.pubhouses напрямую
# валидация
validates :title, :presence => true
validates :title, :uniqueness => true
validates :title, :length => { :maximum => 150 }
validates :description, :length => { :maximum => 2000 }
end
# 'app/models/pubhouse.rb'
class Pubhouse < ActiveRecord::Base
has_many :book_pubhouses, :dependent => :destroy
has_many :shops, :through => :book_pubhouses
validates :title, :presence => true
validates :title, :uniqueness => true
validates :title, :length => { :maximum => 150 }
validates :address, :length => { :maximum => 2000 }
end
# 'app/models/book_pubhouse.rb'
class BookPubhouse < ActiveRecord::Base
belongs_to :book
belongs_to :pubhouse
validates :book_id, :presence => true
validates :pubhouse_id, :presence => true
validates :pubhouse_id, :uniqueness => {:scope => :book_id}
end
<%= form_for(@book) do |f| %>
...
<div class="param">
<%= f.label :pubhouses %>
<span class="ul">
<% Pubhouse.all.each do |pubhouse| %>
<label class="li"><%= check_box_tag :pubhouse_ids, pubhouse.id, @book.pubhouses.include?(pubhouse), :name => 'book[pubhouse_ids][]' %> <u><%= pubhouse.title %></u></label><br />
<% end %>
</span>
</div>
...
<% end %>
<%= form_for(@book) do |f| %>
...
<div class="param">
<%= f.label :pubhouses %>
<%= select_tag("book[pubhouse_ids][]", options_for_select(Pubhouse.all.collect { |pubhouse| [pubhouse.title, pubhouse.id] }, @book.pubhouses.collect { |pubhouse| pubhouse.id}), {:multiple=>true, :size=>5}) %>
</div>
...
<% end %>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment