i working on application send post request rails server parameters stored in json format. let's application routes request create function on cats_controller. cat model has 3 fields :name, :hunger, :mood. each cat has_many kittens. kitten model has 2 fields :cat_id (referring cat owns it, because kitten belongs_to cat) , :cute. every time create cat on application want single call, call /cats.json app post request. parameters stored in json format , include following fields {name:"",hunger:"", mood:"",cute:""}. controller takes these params creates new cat, , creates new kitten assigned cat using cat.kittens.build(). kitten needs use last parameter sent "mood:" created properly.
now question this, when print params variable controller following hash: {name:"", hunger:"", mood:"", cute:"", cat:{name:"", hunger:"", mood:""}}. why happen? how rails parse post request params , take me
{name:"",hunger:"", mood:"",cute:""} {name:"", hunger:"", mood:"", cute:"", cat:{name:"", hunger:"", mood:""}}
how "cat" hash generated, when, , rules follow?
then followup question be, since rails 4 forces whitelist parameters before use them. doing:
params.require(:cat).permit(:name,:hunger,:mood)
how permit :cute value?
you'll best reading on http - difference between , post
.
it's not rails sends request, it's plain old html.
the difference you're looking @ how server picks post
params, considering get
params passed through url...
note query strings (name/value pairs) sent in url of get request:
note query strings (name/value pairs) sent in http message body of post request
thus, base level answer question need append post
params message body of request. best example know of how jquery ajax:
$.ajax({ url: ..., data: {your: key, value: pairs} });
to answer other questions, here's structure should use:
#app/models/cat.rb class cat < activerecord::base #columns id | name | mood | created_at | updated_at has_and_belongs_to_many :kittens class_name: "cat", join_table: :kittens, foreign_key: :cat_id, association_foreign_key: :kitten_id alias_attribute :born, :created_at #-> allows call @cat.born end #kittens table #columns cat_id | kitten_id
you can read self join here: rails: self join scheme has_and_belongs_to_many?
this should give ability create cat, , have him/her assigned kitten of cat:
#app/controllers/cats_controller.rb class catscontroller < applicationcontroller def new @cat = cat.new end def create @cat = cat.new cat_params @cat.save end private def cat_params params.require(:cat).permit(:name, :mood, :kittens) end end
this give ability have following:
#app/views/cats/new.html.erb <%= form_for @cat |f| %> <%= f.text_field :name %> <%= f.text_field :mood %> <%= f.collection_select :kittens, cat.all, :id, :name %> <%= f.submit %> <% end %>
this allow call:
@cat = cat.find params[:id] @cat.kittens.each |kitten| kitten.mood #-> "cute"
Comments
Post a Comment