0

I have a Post model that have a title and content attributes.

I want to make it possible to tweet when the user creates a post like this.

<%= form_for @post do |f| %>
  <%= f.text_field :title %>
  <%= f.text_area :content %>
  <%= f.check_box :with_tweet %> # Error
  <%= f.text_field :tweet %> # Error
<% end %>

This code fails, because there are no with_tweet and tweet attributes for Post. I don't think query strings are good idea situation like this.

How should I send a information that is not related a model?

ironsand
  • 14,329
  • 17
  • 83
  • 176

2 Answers2

3

Define them as virtual attributes:

class Post < ActiveRecord::Base
  ...
  attr_accessor :with_tweet, :tweet
  ...
end

attr_accessor will provide a getter and a setter method for with_tweet and tweet which should then be accessible to you through the @post object.

vee
  • 38,255
  • 7
  • 74
  • 78
2

Further to Vee's answer, let me explain why you'd need it:

Every attribute in a Rails model is the result of using a Ruby getter & setter - meaning that your model's attributes are essentially just parts of a Ruby object, built when your class is initialized

The problem you have is Ruby on Rails does not build any other attributes other than the ones in your DB, meaning if you wanted to track extra data, you'll have to use virtual attributes to let the class know to populate those not in the db

attr_accessor is used to define those extra attributes

Community
  • 1
  • 1
Richard Peck
  • 76,116
  • 9
  • 93
  • 147