How to handle non model data in form?


I got a form which looks like this:
- form_for(@article, :html => {:multipart => true}, :url =>
articles_path) do |f|
  = errors_for(@article)

    = f.label :text
    = f.text_field :text

    = f.label :author_id
    = f.text_field :author_id

    = f.submit

But since I don't want anyone to type in an author id I changed it to:
    = f.label :author_name
    = f.text_field :author_name

added to article.rb:
attr_accessible :author_name

def before_validation
if self.author_name
  author_name = self.author_name.split =

But now this line:
@article =[:article])
throws this error:
unknown attribute: author_name

I thought attr_accessible would cover that? How can I make this work?

I think you probably want 'attr_accessor' instead of 'attr_accessible'.

'attr_accessor' is a Ruby feature that creates getter and setter
methods (#author_name and #author_name=) for an instance variable.

'attr_accessible' is part of Rails' mass-assignment feature; it
white-lists an existing attribute as assignable via mass-assignment.

They're easily confused, thanks to the similar names.



added to article.rb:
attr_accessible :author_name

You should use attr_accessor instead (not attr_accessible, as You
don't have the author_name DB column).

Yes, of course! Thank you guys :slight_smile: