0
votes

I am trying to learn by doing and need some help.

So formtastic can handle belongs_to associations (like Post belongs_to :author), rendering a select or set of radio inputs with choices from the parent model.

What I am trying to do is create a post without having to select the author in the create form.

I want to set the author id via a hidden form field but when I try this

 <%= f.input :author, :as => :hidden, :value => '33' %>

I get uninitialized constant author and tried various other ways that Ive failed to get to work.

The closest Ive got has been by trying to customise the choices for the select and hiding the select as follows:

<%= f.input :author, :as => :select, :collection => ["33"], :input_html => { :style => 'visibility: hidden' } %>

But even though the above hides the select and works, it still displays a form label for author which I dont want it to display

Here is an example to better explain my scenario if what Im trying to achieve is still unclear:

Imagine you have a list of authors page and as an author you click on your name to get into an area where you can manage various things and create posts.

The problem: When you click create a post and the form renders, you dont want to have to select your name from one of the fields to tell the app that the post you are creating belongs to you because you want the system to know its yours because you are in a config area that belongs to you.

I am trying to do this by using a hidden form field to set the author id so that the post is saved with the correct association when the user submits the form.

Can anyone provide me with an example of how to do this? and as Im a learner maybe there is a better way to approach this so can anyone please advise and point me to some good examples

1

1 Answers

0
votes

You should not be populating it in a hidden form field; hidden form fields can still be changed by the user and in the end you are allowing users to create posts by other authors.

The correct way to do this would be to assign @post.author = current_user in the create action of your PostsController.