I have a author model
class Author
include Mongoid::Document
field :name
end
In My article form i want to bring all authors
<div class="field">
<%= f.label :author_tokens, "Authors" %><br />
<%= f.text_field :author_tokens, "data-pre"=> @article.authors.map(&:attributes).to_json %>
</div>
It is working. all authors name are seen. now i want to submit all author name i click inside Authors. what should be my article model for this? I am confuse. Here when i publish
{"utf8"=>"✓",
"authenticity_token"=>"bE0PpLx+qBUJqIavfvpDOjzrhIHFku+IrgjnU0OLOC8=",
"article"=>{"name"=>"ram",
"published_on(1i)"=>"2012",
"published_on(2i)"=>"8",
"published_on(3i)"=>"20",
"author_tokens"=>"",
"content"=>"fdsfds"},
"commit"=>"Create Article"}
author_tokens field is empty.
I have my article model
class Article
include Mongoid::Document
include Mongoid::Timestamps
include Mongoid::MultiParameterAttributes
field :name
field :content
field :author_tokens
field :token_inputs
field :published_on, :type => Date
validates_presence_of :name,:content
has_many :authors
attr_reader :author_tokens
def author_tokens=(ids)
self.author_ids =ids.split
end
end
What should be my article model so that i can save all input author tokens name in my article collection?
On the Article model, try removing:
and adding:
Also, not sure where the
token_inputsfield is getting used. Maybe unnecessary?EDIT:
I overlooked this earlier, but you need
has_and_belongs_to_manyon both sides of the relation for this to even work the way you want, so:and:
To clarify my original explanation:
1) The setter method you wrote for
author_tokensand theattr_reader : author_tokensare both fine, but if you’re using mass assignment in the controller (likely), you need to make theauthor_tokensattribute mass assignable withattr_accessible :author_tokens. Mongoid might do this automatically if you haven’t explicitly set anything else asattr_accessibleyet, depending on what version you’re using.2) You shouldn’t need the
field :author_tokensline since it’s a virtual attribute accessed via the setter you wrote, and theattr_readercall. You don’t actually want to store the value the user passes intoauthor_tokensin the DB, you want the setter to put those values into theauthor_idsfield for you.3) The
has_and_belongs_to_many :authorscall will have created theauthor_idsfield in the document for you.4) Assuming you’re using the pattern shown here, the front-end implementation should be no different when using Mongoid instead of ActiveRecord.