Raczkuję w rails i mam pytanie do grona Ralis-wyjadaczy.
Mam relacje wiele do wielu: authors i books.
[code]ActiveRecord::Schema.define(:version => 20100219154011) do
create_table “authors”, :force => true do |t|
t.string “name”
t.string “surname”
end
create_table “authors_books”, :id => false, :force => true do |t|
t.integer “author_id”
t.integer “book_id”
end
create_table “books”, :force => true do |t|
t.string “title”
t.string “polish_title”
t.string “publisher”
t.string “place”
t.integer “year”
t.string “nr_edition”
t.string “translator_name”
t.string “translator_surname”
end
end[/code]
Chcę aby użytkownik dodawał tworząc nowy egzemplarz książki określił, kto jest jej autorem. Więc w pliku new.html.erb dałem
<%for author in Author.find(:all) %>
<%=check_box_tag "book[author_ids][]", author.id, @book.authors.include?(author)%>
<%="#{author.name} #{author.surname}"%><br/>
<%end%>
Co muszę napisać w kontrolerze book_controller.rb?
Czy aby mi to prawidłowo zadziałało wystarczy, że dam
def create
@book = Book.new(params[:book])
@book.author_ids=params[:book][:author_ids]||=[]
respond_to do |format|
if @book.save
flash[:notice] = 'Book was successfully created.'
format.html { redirect_to(@book) }
format.xml { render :xml => @book, :status => :created, :location => @book }
else
format.html { render :action => "new" }
format.xml { render :xml => @book.errors, :status => :unprocessable_entity }
end
end
end