1

I have a form_for like so:

<%= form_for(@post) do |f| %>

I would like to submit a parameter that is not an attribute of the model

<%= f.text_field :label%>

I have a Label model (labels has_many :posts and posts has_many :labels) and in the create action of the posts_controller I want to create a new Label object based off the label text_field. With the above text_field I get:

undefined method `label'for #<Object>

How can I go about achieving this?

Thanks in advance!

2 Answers 2

11

If your attribute doesn't exist into database table, and still you want to use it, then you have specify that attribute into model by following way

attr_accessor :name, :email, :content
Sign up to request clarification or add additional context in comments.

Comments

0

You can try fields_for method for the creation of associated objects.

<%= form_for(@post) do |f| %>
  <%= fields_for @post.labels do |label| %>
    <%= label.text_field :name %>
    <%= label.text_area :description %>
  <% end %>
<% end %>

To display default number of labels you need to build the associated objects in the controller.

In your posts controller add

def new
  @post = Post.new
  #To build 2 labels use
  2.times do
  @post.labels.build 
  end
end

To accept the nested attributes add below code in your Post model.

class Post < ActiveRecord::Base
  accepts_nested_attributes_for :labels
end

Someone posted this then deleted...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.