Domanda

I'm brand-spankin'-new to rails, so forgive me if this is a stupid question -- i simply cannot piece together enough answers to tell if i started incorrectly. Here goes.

  1. i created everything related to my Company model with rails g scaffold Company name:string description:text location_city:string location_state:string accounttype:references

  2. i created everything related to the Accounttype model with rails g scaffold Accounttype id:primary_key name:string price:decimal

  3. my Company model therefore contains the following allowances:

    belongs_to :accounttype

    attr_accessible :description, :location_city, :location_state, :name

  4. when i go to my scaffold-generated edit form for company, and enter data in those fields, it throws an error: Can't mass-assign protected attributes: accounttype

  5. if I add :accounttype to attr_accessible, it throws Accounttype(#70175254242100) expected, got String(#70175215042700) with the following request params:

    {"utf8"=>"✓", "authenticity_token"=>"oXm3cqo0jemKYFB5OGqn5ixXLSB+bH19/1RhPUu0ZHU=", "company"=>{"name"=>"Acme Corp", "description"=>"a", "location_city"=>"san diego", "location_state"=>"california", "accounttype"=>"1"}, "commit"=>"Create Company"}

So, is my problem that I used :references to link the two models? if that is OK that i used that, then what should I do to get creating/updating to work?

È stato utile?

Soluzione

Congrats on using learning rails! You will have to use accepts_nested_attributes_for in your Company model in order to assign attributes directly to the Accounttype model. Like so:

belongs_to :accounttype

accepts_nested_attributes_for :accounttype

attr_accessible :description, :location_city, :location_state, :name, :accounttypes_attributes

Notice since you are using attr_accessible you have to add accounttypes_attributes Also, I would suggest changing Accounttype to AccountType

sources: Docs Railscast

Altri suggerimenti

You should look into resource nesting and for nested resources use

accept_attributes_for :accounttype

http://masonoise.wordpress.com/2010/07/23/rails-and-forms-using-accepts_nested_attributes_for/

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top