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:
field :author_tokens
and adding:
attr_accessible :author_tokens
Also, not sure where the token_inputs
field is getting used. Maybe unnecessary?
EDIT:
I overlooked this earlier, but you need has_and_belongs_to_many
on both sides of the relation for this to even work the way you want, so:
Class Author
has_and_belongs_to_many :articles
...
end
and:
Class Article
has_and_belongs_to_many :authors
# has_many :authors <- Remove this
...
end
To clarify my original explanation:
1) The setter method you wrote for author_tokens
and the attr_reader : author_tokens
are both fine, but if you're using mass assignment in the controller (likely), you need to make the author_tokens
attribute mass assignable with attr_accessible :author_tokens
. Mongoid might do this automatically if you haven't explicitly set anything else as attr_accessible
yet, depending on what version you're using.
2) You shouldn't need the field :author_tokens
line since it's a virtual attribute accessed via the setter you wrote, and the attr_reader
call. You don't actually want to store the value the user passes into author_tokens
in the DB, you want the setter to put those values into the author_ids
field for you.
3) The has_and_belongs_to_many :authors
call will have created the author_ids
field 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.