First of all I'm no native speaker and just begun with rails three days ago. Sorry for my mistakes. Formtastic is driving me crazy. I have three tables: user, note, receiver:
class User < ActiveRecord::Base
has_many :receivers
has_many :notes, :through => :receivers
attr_accessible :id, :email, :password, :password_confirmation, :remember_me
class Note < ActiveRecord::Base
has_many :receivers
has_many :users, :through => :receivers
attr_accessible :id, :text, :user_id
accepts_nested_attributes_for :receivers
class Receiver < ActiveRecord::Base
belongs_to :user
belongs_to :note
attr_accessible :user_id, :note_id, :note_attributes
accepts_nested_attributes_for :user
accepts_nested_attributes_for :note
And here my formtastic form:
<%= semantic_form_for @note do |form| %>
<%= form.inputs do %>
<%= form.input :text %>
<%= form.input :user_id, :as => :check_boxes, :collection => User.find(:all, :conditions => ["id != ?", current_user.id], :order => 'id').collect{|u| [u.email, u.id]} %>
<% end %>
<%= form.butt开发者_StackOverflowons %>
<% end %>
Now I want to create a new note which can have several receivers. Unfortunately only the note is created, but no entrys in the receiver table, even if I select receivers. Can someone help me please?
Here my notes_controller:
@note = Note.new(params[:note])
Print out the params[:note] using logger.info and check what all parameters are passed from form and Can you also try adding code
reciever_ids code
as attr_accessible in Note model
In the view model, you are using attr_accessible, it wont save any fields that are not in the attr_accessible like the receives_attributes, that comes from the form when your nested form is displayed. So you have to add receiver_attributes to the attr_accessible list.You might want to do this to the User and Receiver(if you are having nested forms for them too), which also have attr_accessible
attr_accessible :id, :text, :user_id, :receiver_attributes
In the new action of notes_controller, you need to use build method like
@note.build_receiver
then in the form, you need to write the code to display the fields in the receiver.
<%= semantic_form_for @note do |form| %>
<%= form.inputs do %>
<%= form.input :text %>
<%= form.input :user_id, :as => :check_boxes, :collection => User.find(:all, :conditions => ["id != ?", current_user.id], :order => 'id').collect{|u| [u.email, u.id]} %>
<% end %>
<%=f.semantic_fields_for :receiver_attributes, @note.receiver do|receiver| %>
<!-- Add receiver related input here using the receiver block variable like receiver.input -->
<% end %>
<%= form.buttons %>
<% end %>
精彩评论